简体   繁体   中英

Position legend in first plot of facet

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:

情节与外面的传说

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

里面有传说的情节

Thanks for any help you can provide!

Assuming your plot is saved as p

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM