问题已解决
# 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)
使用rect
选项也可以使用annotate
来完成类似的任务:
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")
以下是生成的图表:
不幸的是,注释区域超出了柱形图。目前还没有找到解决方法。如果有人正在寻找类似的解决方案,希望这能帮到你。