组合居中图例

Combined centered legend

我正在使用 patchwork 创建一个组合图,其中有一个位于顶部居中的公共图例。

library(ggplot2)
library(patchwork)

x1 <- ggplot(iris,aes(Sepal.Width, Petal.Length, col=Species))+
       geom_point()

x2 <- ggplot(iris,aes(Petal.Width, Petal.Length, col=Species))+
       stat_ellipse(show.legend=F)

wrap_plots(x1, x2, guides="collect") +
  theme(legend.position="top",
        legend.direction="horizontal")

这就是我得到的。

这是我所期待的。

ggpubr::ggarrange(x1, x2, common.legend=T)

问题是您使用的是 + 而不是 &。运算符的区别见here

  1. 使用 + 时,主题层仅应用于最后一个情节,即 x2 在您的情况下没有图例
  2. 如果你想应用到所有地块,你必须使用 &
library(ggplot2)
library(patchwork)

x1 <- ggplot(iris,aes(Sepal.Width, Petal.Length, col=Species))+
  geom_point()

x2 <- ggplot(iris,aes(Petal.Width, Petal.Length, col=Species))+
  stat_ellipse(show.legend=F)

wrap_plots(x1, x2, guides="collect") &
  theme(legend.position="top",
        legend.direction="horizontal")