Is it possible to place the legend in the upper right corner of ggplot in R?

I am trying to create a theme for ggplot, which I can then use for all my graphs and get them both pleasant and pleasant and homogeneous. I want to move the legend from its current position, vertically centered on the right, to be aligned with the top of the graph on the right, as shown by the red arrow below.

Desired legend movement

I can not understand. I can force it to be positioned inside the plot using legend.position , but if I then make legend.justification = c(0.0, 1.0) , it pops the legend outside the area that it is plotting, and it completely turns off. I know that I could do this individually for each graph, combining with grobs and gtables for each individual graph, but I do not want to do this every time I draw a graph.

Is there any way to do this using theme ?

+8
r ggplot2
source share
4 answers

It seems like this is 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") 
+6
source share

Try experimenting with theme options, in particular

  • legend.key.width
  • plot.margin

Try the following:

 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

+5
source share
 library(ggplot2) p <- ggplot(iris, aes(Sepal.Length, Sepal.Width, col=Species)) + geom_point() + theme(legend.background = element_rect(colour = "black", size = 0.5), panel.background = element_rect(colour = "black", size = 0.5)) g <- ggplotGrob(p) leg <- g$grobs[[8]] leg$heights[3] <- unit(1,"null") leg$heights[1] <- unit(0,"null") # grid.newpage() # grid.draw(leg) g$grobs[[8]] <- leg grid.newpage() grid.draw(g) 

enter image description here

+3
source share

The easiest hack I've found

 ggplot(data.frame(x=1:3, y=1:3), aes(x=x, y=y, colour=x)) + geom_point() + theme(plot.margin=unit(c(5,5,1,1),"cm"), legend.position=c(1.1, 1.1)) 

You can also play with the legend.justification parameter by setting it, for example. to "top" . enter image description here

0
source share

All Articles