ggplot2 - 在堆叠条形图中更改`geom_rect`颜色

8

我想使用ggplot2::geom_bar绘制堆叠柱状图,并根据一个分类变量设置背景阴影(使用ggplot2::geom_rect()),方法如下:

shading <- data.frame(min = seq(from = 0.5, to = max(as.numeric(as.factor(diamonds$clarity))), by = 1),
                      max = seq(from = 1.5, to = max(as.numeric(as.factor(diamonds$clarity))) + 0.5, by = 1),
                      col = c(0,1))

ggplot() + 
  theme(panel.background = element_rect(fill = "transparent")) +
  geom_bar(data = diamonds, mapping = aes(clarity, fill=cut)) +
  geom_rect(data = shading,
            aes(xmin = min, xmax = max, ymin = -Inf, ymax = Inf,
                fill = factor(col), alpha = 0.1)) +
  geom_bar(data = diamonds, mapping = aes(clarity, fill=cut)) +
  guides(alpha = FALSE)

在这里输入图片描述

如何更改阴影颜色?我尝试了 scale_fill_manual(values = c("white", "gray53")),但似乎ggplot2中不允许多个比例美学 (https://github.com/hadley/ggplot2/issues/578)。是否有其他方法可以获得所需的结果?

1个回答

14

是的,与其将颜色放在aes()中,不如将它们放在外面(以原样使用)。由于它在aes()调用之外,因此您将不得不使用显式的fill=shading$col而不是fill=col,并且shading$col应该具有您想要的颜色名称(而不是解释为因子的变量)。

shading$col <- ifelse(shading$col, 'white', 'gray53')
ggplot() + 
  theme(panel.background = element_rect(fill = "transparent")) +
  geom_bar(data = diamonds, mapping = aes(clarity, fill=cut)) +
  geom_rect(data = shading,
            aes(xmin = min, xmax = max, ymin = -Inf, ymax = Inf, alpha = 0.1),
                fill=shading$col) + # <-- here
  geom_bar(data = diamonds, mapping = aes(clarity, fill=cut)) +
  guides(alpha = FALSE)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接