6

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)
Community
  • 1
  • 1
Adela
  • 1,757
  • 19
  • 37

2 Answers2

8

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

zx8754
  • 52,746
  • 12
  • 114
  • 209
2

You can try this:

library(ggplot2)
data("mtcars")
g <- ggplot(mtcars, aes(wt, mpg))
g <- g + geom_point(aes(colour = factor(cyl), size = qsec))
g <- g + geom_point(aes(colour = factor(cyl), size = qsec))
g <- g + theme(legend.justification=c(0,0), legend.position=c(0,0))

For other positions you can try from this documentation http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/

enter image description here

Probably you will find better explanation also in the above link.

krishna Prasad
  • 3,541
  • 1
  • 34
  • 44
  • If you look closely legends are not aligned on the left side, that was the OP's problem. – zx8754 Apr 13 '16 at 08:09
  • @zx8754 I did not get you completely, does it mean that legends should touches the inside plots boundary in the left side? – krishna Prasad Apr 13 '16 at 08:20
  • @krishna: Unfortunately, your post does not solve my problem, because I need both legends to be left-sided aligned. As zx8754 has written, if you look closer, you can see that they are still centered - only the position of legends has been changed. zx8754 already solved my problem (see previous post). Anyway, thanks for trying! – Adela Apr 13 '16 at 08:27
  • Sorry, I wasn't clear enough, in your plot, yes legends are on the left side of the plot, but 2 legends are not aligned on the left side - they are centered. – zx8754 Apr 13 '16 at 08:33