36

I would like to put my plot legend inside the plot, inside the first plot of a facet.

Here is some example code:

df=data.frame(
 x=runif(10),
 y=runif(10),
 facet=rep(c("a","b"),5),
 color=rep(c("red","blue"),5))

ggplot(data=df,aes(x=x,y=y,color=color))+
 geom_point()+
 facet_wrap(~facet,ncol=1)

Here is the resulting plot:

plot with legend on outside

And here is roughly how I would like it to look:

plot with legend inside

Thanks for any help you can provide!

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
jslefche
  • 4,379
  • 7
  • 39
  • 50

2 Answers2

33

Assuming your plot is saved as p

p + theme(
  legend.position = c(0.9, 0.6), # c(0,0) bottom left, c(1,1) top-right.
  legend.background = element_rect(fill = "white", colour = NA)
)

If you want the legend background partially transparent, change the fill to, e.g., "#ffffffaa".

Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • Thanks Richie! That works on my example plot, but for some reason when I add those lines of code to another plot, the legend disappears. Any idea why that might be? I put the opts code I have in the original post – jslefche Sep 01 '11 at 13:39
  • Was the other plot saved to a file type that didn't support transparency (maybe a gif)? – Richie Cotton Sep 01 '11 at 13:44
  • Or did you change the `legend.position` so that it was moved of the edge of the plot? – Richie Cotton Sep 01 '11 at 13:45
  • It was moved off the plot...the values in `legend.position` don't agree with the values on the x-axis, for some reason. I seem to have it now – jslefche Sep 01 '11 at 13:52
  • 2
    The values that legend position uses are relative to the plotting area, so `c(0,0)` is the bottom left of your plot and `c(1,1)` is the top right. They can't be the same as the values on the x-axis, since different facets can have different scales. – Richie Cotton Sep 01 '11 at 15:23
21

Or, building on @Richie Cotton's answer, since opts is deprecated in ggplot2 now (still assuming your plot is defined as p)

p + theme(legend.position = c(0.9, 0.6)
          ,legend.background = element_rect(fill = "white", colour = NA))
Nova
  • 5,423
  • 2
  • 42
  • 62