I am trying to justify multiple legend in ggplot, but without any real success. When displaying legend outside plot region (grey area) justification is correct. However, when displaying legends inside plot region, legends are centered (and I would like to make them be left-sided aligned). I have tried to follow this thread but it still does not work properly.
My example:
library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) +
geom_point(aes(colour = factor(cyl), size = qsec)) +
geom_point(aes(colour = factor(cyl), size = qsec)) +
theme(legend.justification = c(1,0),
legend.position = c(1,0),
legend.margin = unit(0,"lines"),
legend.box = "vertical",
legend.key.size = unit(1,"lines"),
legend.text.align = 0,
legend.title.align = 0)
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 . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.
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.
By specifying legend. position=”none” you're telling ggplot2 to remove all legends from the plot.
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
We need to add legend.box.just = "left"
into your existing theme()
.
ggplot(mtcars, aes(wt, mpg)) +
geom_point(aes(colour = factor(cyl), size = qsec)) +
geom_point(aes(colour = factor(cyl), size = qsec)) +
theme(legend.box.just = "left",
legend.justification = c(1,0),
legend.position = c(1,0),
legend.margin = unit(0,"lines"),
legend.box = "vertical",
legend.key.size = unit(1,"lines"),
legend.text.align = 0,
legend.title.align = 0)
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