3

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."

rcs
  • 67,191
  • 22
  • 172
  • 153
jsuprr
  • 97
  • 1
  • 6

1 Answers1

2

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.)

user2034412
  • 4,102
  • 2
  • 23
  • 22
  • I tried your code. For the margins part, I get: Error: could not find function "unit" . **EDIT**: Turns out you need to attach the grid package to use unit command. It works perfectly now. Thanks! – jsuprr Apr 23 '15 at 13:54