Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple legend justification

Tags:

r

legend

ggplot2

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)
like image 413
Adela Avatar asked Apr 13 '16 07:04

Adela


People also ask

How do I change the legend position in R?

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.

How do I add a legend in ggplot2?

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.

How do I get rid of the legend in ggplot2?

By specifying legend. position=”none” you're telling ggplot2 to remove all legends from the plot.

How do I change the legend text in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))


1 Answers

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)

enter image description here

like image 126
zx8754 Avatar answered Oct 10 '22 13:10

zx8754