将 ggplot2 中的图例与拼凑而成(离散/分类数据)组合和合并

Geg*_*naV 5 r ggplot2 patchwork

我使用patchwork包的功能将 3 个ggplot2图排列成一个图形。我试图收集这些图例,结果它们一个接一个地出现。但尽管如此,他们仍然是 3 个独立的传奇,而我原本以为只有一个传奇。那么如何将包含相同因子变量的相同值的图例合并到单个图例中呢?

笔记:

  1. 我不想通过使用来删除单独图的图例,例如,theme(legend.position = "none")以防出现一些附加因素水平。我期待拼凑出具体的解决方案。
  2. 类似的问题在“Combine and merge legends in ggplot2 with patchwork”中得到了回答,但数据是连续的。就我而言,我有分类数据。

代码:

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")
Run Code Online (Sandbox Code Playgroud)

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


更新

我尝试使用与下面的评论中提议的相同的美学映射(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")
Run Code Online (Sandbox Code Playgroud)

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

ste*_*fan 3

不幸的是,设置相同的 aes 只是一个条件。仅当图例相同时,拼凑才会合并图例。因此,我们必须确保每个图例的图例都是相同的。为此,我添加了一个图层,通过设置、和guides使每个图例的外观相同。此外,我们必须使用参数为每个几何图形选择相同的字形。经过这些调整后,三个图例合二为一。colorshapesizealphakey_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")
Run Code Online (Sandbox Code Playgroud)