Is there another way to change legend position for ggplot?

I need my legend to be inside the plot itself (for space reasons). Currently I have the legend hardcoded to specific position using legend.position = c(.85,.75).

I am making hundreds of variations these plots and sometimes the lines being plotted end up being covered by the legend. However since I am making hundreds it also means I don't have time to manually go through and change the legend position for every variation with this issue.

Is there an existing option for legend position that puts the legend in the plot area but is smart enough to move the legend so it doesn't cover any of the plotted data? I know there are some ways when labeling points to make sure they jitter so they don't cover any data and I am curious if something similar exists for the legend?

You can use legend. position = "bottom" or "top"

I can't have the legend outside the plot area because of a spacing issue so using legend.position set to 'top', 'bottom', 'right', or 'left' is out.

As a theoretical matter, I don't see how this guaranteed, as your points might cover the space of your plot, leaving nowhere empty to draw a legend ? Or is it acceptable to fail in some cases ?

I am plotting densities so I know I will get normal-ish looking bell curves. The issue is sometimes the skew changes so the area of greatest density can move. I know for this particular plot I will never get a plot with a totally even distribution of points, there will always be a blank spot to stick the legend. The issue is just identifying that spot.

My ideal solution would to have something built in where I could tell ggplot to have the legend dodge the plotted data. But I am also open to just building my own algorithm for changing the legend position. I can very easily tell where my points will end up the issue is I can't figure out how to determine the area of the legend.

hmm, from your description it seems that you could simplify to a problem about putting the legend in one of two predetermined positions. i.e. Either a) top left or b) top right, depending on the skew; and you can find the skewness from the data to make that choice .
might that be a way to go ?

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.