r - 在 ggplot2 的条形图中为分类变量添加阴影替代区域

标签 r ggplot2 visualization

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

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

enter image description here

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

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

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

enter image description here

最佳答案

解决了

# 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)

enter image description here

关于r - 在 ggplot2 的条形图中为分类变量添加阴影替代区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31592484/

相关文章:

apache-spark - Graphx可视化

android - 带圆圈的简单音乐可视化

r - 如何在ggplot中向条形图添加文本

r - 强制 Shiny 的应用程序在移动设备上显示桌面 View

r - 如何让 R 在读取 CSV 时插入 '0' 来代替缺失值?

r - ggplot2:在右侧为一个变量创建第二个 y 轴

c# 代码流映射/可视化实用程序?

R:如何在 ggplot2 线图中重新排序图例键以匹配每个系列中的最终值?

r - ggplot2 分组直方图条

r - 具有可变字体系列的 geom_text 图例