2

我使用包patchwork的功能将 3 个ggplot2图排列成一个图形。我试图收集传说,它们一个接一个地出现。但是,它们仍然是 3 个独立的传说,我希望只有一个传说。那么如何将包含相同因子变量的相同值的图例合并到一个图例中呢?

笔记:

  1. 而且我不想通过使用来删除单独图的图例,例如,theme(legend.position = "none")以防出现一些额外的因子水平。我期望拼凑特定的解决方案。
  2. 在 ggplot2 中用拼凑的组合和合并图例中回答了一个类似的问题,但数据是连续的。就我而言,我有分类数据。

编码:

library(ggplot2)
library(patchwork)

iris_1 <-
  ggplot(iris, aes(x = Sepal.Length, fill = Species, color = Species)) +
  geom_density(alpha = 0.3, adjust = 1.5)

iris_2 <-
  ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point()

iris_3 <-
  ggplot(iris, aes(x = Species, y = Sepal.Width, fill = Species)) +
  geom_boxplot()


(iris_1 + iris_2 + iris_3) + plot_layout(guides = "collect")

reprex 包(v0.3.0)于 2020 年 10 月 14 日创建


更新

我尝试使用与以下评论中提出的相同的美学映射(fill = Speciescolor = Species),但没有效果:

library(tidyverse)
library(patchwork)

iris_1 <-
  ggplot(iris, aes(x = Sepal.Length, color = Species, fill = Species)) +
  geom_density(alpha = 0.3, adjust = 1.5)

iris_2 <-
  ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species, fill = Species)) +
  geom_point()

iris_3 <-
  ggplot(iris, aes(x = Species, y = Sepal.Width, color = Species, fill = Species)) +
  geom_boxplot(color = "black")

(iris_1 + iris_2 + iris_3) + plot_layout(guides = "collect")

reprex 包(v0.3.0)于 2020 年 10 月 14 日创建

4

1 回答 1

1

不幸的是,设置相同的 aes 只是一个条件。只有当图例相同时,拼凑才会合并图例。因此,我们必须确保每个图的图例都相同。为此,我添加了一个图层,guides通过设置color、和使每个图例的外观相同。此外,我们必须使用参数为每个几何图形选择相同的字形。在这些调整之后,三个图例合并为一个。shapesizealphakey_glyph

library(ggplot2)
library(patchwork)

g <- guides(fill = guide_legend(override.aes = list(color = scales::hue_pal()(3),
                                                    shape = c(16, 16, 16), 
                                                    size = c(1, 1, 1),
                                                    alpha = c(1, 1, 1)),))

iris_1 <-
  ggplot(iris, aes(x = Sepal.Length)) +
  geom_density(aes(fill = Species, color = Species), key_glyph = "point", alpha = 0.3, adjust = 1.5) +
  g

iris_2 <-
  ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(fill = Species, color = Species), key_glyph = "point") +
  g

iris_3 <-
  ggplot(iris, aes(x = Species, y = Sepal.Width)) +
  geom_boxplot(aes(fill = Species, color = Species), key_glyph = "point") +
  scale_color_manual(values = c("black", "black", "black")) +
  g


(iris_1 + iris_2 + iris_3) + plot_layout(guides = "collect")

于 2020-10-14T10:03:01.520 回答