Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to position the legend to the top right of a ggplot in R?

Tags:

I am trying to create a theme for ggplot that I can then use for all my graphs and getting them looking both nice and nice and uniform. I want to move the legend from its current position vertically centred on the right to being aligned with the top of the graph on the right, as indicated by the red arrow below.

Desired legend movement

I cannot figure it out. I can get it to position inside the plot by using legend.position but if I then do legend.justification = c(0.0, 1.0) it pushes the legend outside of the area it plots and it gets cut off completely. I know I could do it individually for each graph by messing around with grobs and gtables for each individual graph but I don't want to have to do that every time I plot a graph.

Is there anyway to do this with a theme?

like image 200
Jack Aidley Avatar asked Aug 15 '14 14:08

Jack Aidley


People also ask

How do I move the legend to the top right in R?

Data Visualization using R Programming justification argument. To set the legend on top-right side we can use legend. position="top" and legend. justification="right".

How do you put a legend at the top right?

Click Add Chart Element > Legend. To change the position of the legend, choose Right, Top, Left, or Bottom. To change the format of the legend, click More Legend Options, and then make the format changes that you want.

How do I move the legend in ggplot2?

For Moving the position of ggplot2 legend at any side of the plot, we simply add the theme() function to geom_point() function.

How do I add a legend to Ggplot?

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


2 Answers

Seems like it's finally possible with ggplot2 2.2.0

enter image description here

library(ggplot2) ggplot(mpg, aes(displ, hwy, colour=fl)) +    geom_point() +    theme(legend.justification = "top") 
like image 131
rmf Avatar answered Nov 02 '22 01:11

rmf


Try experimenting with the theme options, in particular

  • legend.key.width
  • plot.margin

Try this:

library(ggplot2)  ggplot(iris, aes(Sepal.Length, Sepal.Width, col=Species)) +      geom_point() +      theme(         legend.position=c(1,1),          legend.justification=c(0, 1),          legend.key.width=unit(1, "lines"),          plot.margin = unit(c(1, 5, 0.5, 0.5), "lines")     ) 

enter image description here

like image 44
Andrie Avatar answered Nov 02 '22 02:11

Andrie