如何在用 ggplot2 制作的单个图中组合填充(列)和颜色(点和线)图例?

How to combine fill (columns) and color (points and lines) legends in a single plot made with ggplot2?

在图表中我有列和点。我试图统一传说;我已经把同一个名字放在秤上了,但它们看起来还是分开的。有人可以帮我解决这个问题吗?

library(ggplot2)

X <- factor(c("a", "b"))
Y1 <- c(10, 15)
Y2 <- c(22, 23)

df <- data.frame(X, Y1, Y2)

ggplot(data = df, aes(x = X,
                      group = 1)) +
  geom_col(aes(y = Y1,
               fill = "Y1")) +
  geom_line(aes(y = Y2,
                color = "Y2")) +
  geom_point(aes(y = Y2,
                 color = "Y2")) +
  scale_fill_manual(name = "Legend",
                    values = "blue") +
  scale_color_manual(name = "Legend",
                     values = "red")

要合并图例,您还必须在填充和色阶中使用相同的值。此外,您必须使用 guide_legend:

override.aes 参数移除“Y2”图例键的填充颜色,稍微调整图例

编辑 感谢@aosmith 的评论。为了使这种方法适用于 ggplot2 版本 <=3.3.3,我们必须显式设置两个尺度的 limits

library(ggplot2)

X <- factor(c("a", "b"))
Y1 <- c(10, 15)
Y2 <- c(22, 23)

df <- data.frame(X, Y1, Y2)

ggplot(data = df, aes(x = X,
                      group = 1)) +
  geom_col(aes(y = Y1,
               fill = "Y1")) +
  geom_line(aes(y = Y2,
                color = "Y2")) +
  geom_point(aes(y = Y2,
                 color = "Y2")) +
  scale_fill_manual(name = "Legend",
                    values = c(Y1 = "blue", Y2 = "red"), limits = c("Y1", "Y2")) +
  scale_color_manual(name = "Legend",
                     values = c(Y1 = "blue", Y2 = "red"), limits = c("Y1", "Y2")) +
  guides(color = guide_legend(override.aes = list(fill = c("blue", NA))))

另一种选择是只制作一个图例,然后手动更改该图例以使其代表所有图层。

在这种情况下,我制作了一个 fill 图例,但将 color 设置为 aes() 之外的常量。我通过添加 show.legend = TRUE.

强制包含 line/point 层

然后我将额外的值添加到 fill,在 scale_fill_manual() 中同时设置 valueslimits。请注意,我将 Y2 设置为透明填充。

最后,我对图例进行了手动更改,以仅保留 guide_legend() 中具有 override.aes 的第二个图例键的线条和点。

ggplot(data = df, aes(x = X,
                      group = 1)) +
    geom_col(aes(y = Y1,
                 fill = "Y1")) +
    geom_line(aes(y = Y2), color = "red", show.legend = TRUE) +
    geom_point(aes(y = Y2), color = "red", show.legend = TRUE) +
    scale_fill_manual(name = "Legend",
                      values = c(Y1 = "blue", Y2 = "transparent"),
                      limits = c("Y1", "Y2")) +
    guides(fill = guide_legend(override.aes = list(shape = c(NA, 19),
                                                   linetype = c(0, 1))))

reprex package (v2.0.0)

于 2021-06-29 创建