首页 > 解决方案 > 如何在使用 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")

在此处输入图像描述

标签: rggplot2scalelegendlegend-properties

解决方案


要合并图例,您还必须在填充和色标中使用相同的值。override.aes此外,您必须通过使用以下参数删除“Y2”图例键的填充颜色来稍微调整图例guide_legend

编辑感谢@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))))


推荐阅读