【问题标题】:Adding shading alternate areas for categorical variable in a bar plot in ggplot2在ggplot2的条形图中为分类变量添加阴影替代区域
【发布时间】:2015-07-23 15:59:24
【问题描述】:

我正在尝试使用ggplot2 绘制条形图,如下所示:

library(ggplot2)
ggplot(mtcars, aes(factor(carb))) +
  geom_bar() +
  coord_flip()

x 轴是一个连续变量,而 y 轴是一个分类变量 (factor)。

我想在每个条形后面添加备用阴影区域以区分 y 轴上的因素。我知道我可以为此使用geom_rect()。当它是factor 时,如何计算该区域的 y 轴范围?矩形的 x 轴范围为 -InfInf

我正在寻找与此图像类似的东西,但要寻找条形图而不是箱线图。

【问题讨论】:

    标签: r ggplot2 visualization


    【解决方案1】:

    解决了

    # Create data.frame with shading info
    shading <- data.frame(min = seq(from = 0.5, to = max(as.numeric(as.factor(mtcars$carb))), by = 1),
               max = seq(from = 1.5, to = max(as.numeric(as.factor(mtcars$carb))) + 0.5, by = 1),
               col = c(0,1))
    
    # Plot
    ggplot() +
      geom_bar(data = mtcars, mapping = aes(factor(carb))) +
      geom_rect(data = shading,
                aes(xmin = min, xmax = max, ymin = -Inf, ymax = Inf,
                    fill = factor(col), alpha = 0.1)) +
      scale_fill_manual(values = c("white", "gray53")) +
      geom_bar(data = mtcars, mapping = aes(factor(carb))) +
      coord_flip() +
      guides(fill = FALSE, alpha = FALSE)
    

    【讨论】:

      【解决方案2】:

      也许沿着这些思路,您可以将颜色不同的较宽阴影条与较暗的较小条重叠?

      ggplot(mtcars, aes(factor(carb))) +
        geom_bar(width = 1.1, aes(x = factor(carb), fill = ifelse(mtcars$carb %in% c(1,3,6), "blue", "transparent"))) +
        guides(fill = FALSE) +
        geom_bar(width = 0.7) +
        scale_fill_manual(values = c("transparent", "blue")) +
        coord_flip()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-29
        相关资源
        最近更新 更多