3

I have three plots p1, p2 and p3. I would like to combine p2 and p3 and add the legends of p2 and p1 on the right side above each other. In the following example the legends are identical. In the real data they are differend.

I use ggplot2 and cowplot

# plot 1
p1 <- ggplot(iris, aes(Sepal.Length, fill = Species)) +
  geom_density(alpha = .7) 


# plot 2
p2 <- ggplot(iris, aes(Sepal.Width, fill = Species)) +
  geom_density(alpha = .7)

# plot 3
p3 <- ggplot(iris, aes(Petal.Width, fill = Species)) +
  geom_density(alpha = .7)


# legend1

legend1 <- get_legend(p1)

# legend2

legend2 <- get_legend(p2)

# combine plots
prow <- plot_grid( p2 + theme(legend.position="none"),
                   p3 + theme(legend.position="none"),
                   align = 'vh',

                   labels = c("a", "b"),

                   hjust = -1,

                   nrow = 1,
                   axis="1"

)

prow

# add legend1
p <- plot_grid( prow, legend1, rel_widths = c(1, .3))
p
# add legend2
plot_grid(p, legend2, rel_widths =c(1, .3))

This gives me this: Result

What I try to get is: Wish

I tried to solve the problem using

+ theme(legend.position=c()

and

+ theme(legend.justification = "top"))

however, I could not get the desired plot.

captcoma
  • 1,768
  • 13
  • 29

1 Answers1

3

You're actually very close. You can use ggdraw to achieve what you want. See ?get_legend for another example of this.

# combine plots
prow <- ggdraw(
  plot_grid(
    plot_grid(p2 + theme(legend.position="none") ,
               p3 +theme(legend.position="none"),
               align = 'vh',

               labels = c("a", "b"),

               hjust = -1,

               nrow = 1,
               axis="1"),
# as suggested by aosmith you can add additional columns to make legends appear closer
    plot_grid(legend1, legend2,ncol=4),
# I also set the relative widths so the legend takes up less space
nrow=1, rel_widths = c(1,0.2))
  )

prow

enter image description here

Chris
  • 3,836
  • 1
  • 16
  • 34
  • 2
    If you want the legends closer together (as in the OP's desired output example), you could add extra (empty) rows: `plot_grid(legend1, legend2, nrow = 4)`. I didn't seem to need an extra `grid_draw` to make things work, but including the `rel_widths` code from the OP made the legend grid take up less space. – aosmith May 31 '18 at 17:09
  • @aosmith yes there is too much white space on the right - I will update the answer to include the `rel_widths` parameter. Your suggestion to make the legends closer is also a good one – Chris May 31 '18 at 17:19