Cro*_*ops 2 visualization r ggplot2
我正在尝试使用ggplot2以下方法绘制条形图:
library(ggplot2)
ggplot(mtcars, aes(factor(carb))) +
geom_bar() +
coord_flip()
Run Code Online (Sandbox Code Playgroud)
x轴是连续变量,而y轴是绝对变量(factor)。
我想在每个条形后面添加备用阴影区域,以区分y轴上的因子。我知道我可以用geom_rect()这个。当它是a时,如何计算该区域的y轴限制factor?X轴为矩形限制将是-Inf到Inf。
我正在寻找与此图像类似的东西,但要寻找条形图而不是盒形图。
解决了
# 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)
Run Code Online (Sandbox Code Playgroud)