用旁边其他地块的图例绘制多个地块

plot multiple plots with legends from other plots beside

我有三个地块 p1p2p3。 我想合并 p2p3 并在右侧添加 p2p1 的图例。在以下示例中,图例是相同的。在实际数据中它们是不同的。

我使用 ggplot2cowplot

# 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))

这给了我这个:

我试图得到的是:

我尝试使用

解决问题
+ theme(legend.position=c()

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

然而,我无法得到想要的情节。

其实你很亲近。您可以使用 ggdraw 来实现您想要的。有关此的另一个示例,请参阅 ?get_legend

# 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