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

Adding shading alternate areas for categorical variable in a bar plot in ggplot2

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

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

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

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

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

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

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

解决了

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

也可以使用 annotaterect 选项来完成类似的任务:

ggplot(data = mtcars) +
  annotate('rect', xmin = c('1.5','3.5', '7'), xmax = c('2.5','4.5','8.5'), 
  ymin=-Inf, ymax=Inf, alpha=0.2, fill="red") +
  scale_fill_manual(values = c("white", "gray53")) +
  geom_bar(data = mtcars, mapping = aes(factor(carb))) +
  coord_flip() +
  scale_x_discrete(breaks=levels(factor(mtcars$carb))) + 
  guides(fill = "none", alpha = "none")

这是结果图:

不幸的是,注释区域溢出了条形图。找不到纠正此问题的方法。如果有人正在寻找类似的解决方案,希望这会有所帮助。