【问题标题】:ggplot2 - Change `geom_rect` colour in a stacked barplotggplot2 - 在堆积条形图中更改“geom_rect”颜色
【发布时间】:2015-07-23 22:28:56
【问题描述】:

我正在尝试根据分类变量使用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) 中似乎无法实现多尺度美学。有没有其他方法可以得到想要的结果?

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    是的,不要将您的颜色放在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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-08
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 2019-01-14
      • 1970-01-01
      • 2017-09-29
      相关资源
      最近更新 更多