Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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!

like image 309
jslefche Avatar asked Sep 01 '11 13:09

jslefche


People also ask

How do I change the position of my legend in R?

position. You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left .

What is facet in plot?

Facet plots, also known as trellis plots or small multiples, are figures made up of multiple subplots which have the same set of axes, where each subplot shows a subset of the data.

Why doesn't my Ggplot have a legend?

If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.

How do I get rid of the legend in ggplot2?

Example 1: Remove All Legends in ggplot2 We simply had to specify legend. position = “none” within the theme options to get rid of both legends.


1 Answers

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, e.g., "#ffffffaa".

like image 100
Richie Cotton Avatar answered Sep 21 '22 13:09

Richie Cotton