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.
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
?
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".
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.
For Moving the position of ggplot2 legend at any side of the plot, we simply add the theme() function to geom_point() function.
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.
Seems like it's finally possible with ggplot2 2.2.0
library(ggplot2) ggplot(mpg, aes(displ, hwy, colour=fl)) + geom_point() + theme(legend.justification = "top")
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") )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With