1
votes

I want to move my ggplot2 legend to the corner, but not inside the plot itself. So it should be in the margin still, but not in the center. The only options I've found are for either selecting "top," "right," etc., or using a custom coordinate within the plot itself.

So for example, take this image:

Hadley Plot](http://i.imgur.com/wpuuZoZ.png)

and imagine sliding the legend straight down from where it currently is to the bottom-right corner.

I tried setting the legend position to c(12, 2) for example, but it just disappears.

Setting it to "right" is what the current image is, but I need the legend to slide down to the "bottom-right."

1
Would it be acceptable to expand the x axis up to 12 with (scale_x_continuous() and use that extra space?lawyeR
Creative, but no. It needs to be polished enough for a VP's eyes.jsuprr

1 Answers

1
votes

You can expand the plot margins and then set the legend position to somewhere outside the plot.

Create your data:

dat = data.frame(x=1:10, y=10:1, type=rep(c('a', 'b'), each=5))

Use the plot.margin and legend.position elements in theme. First create a unit object with your margins:

margins = unit(c(1, 4, 1, 1), 'lines')

Then call ggplot with the margins and legend position.

ggplot(dat, aes(x, y, color=type)) + 
    geom_point() +
    theme(plot.margin=margins,
          legend.position=c(1.075, 0))

(The legend position is usually set between 0 and 1 (using normalized parent coordinates), not the actual x and y coordinates of the plot.)