本文介绍了在ggplot2的条形图中为类别变量添加阴影替代区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用ggplot2
绘制条形图,如下所示:
I am trying t o plot a bar plot using ggplot2
as follows:
library(ggplot2)
ggplot(mtcars, aes(factor(carb))) +
geom_bar() +
coord_flip()
x轴是连续变量,而y轴是绝对变量(factor
).
x axis is a continous variable, while y axis is a categorical one (factor
).
我想在每个条形后面添加备用阴影区域,以区分y轴上的因子.我知道我可以为此使用geom_rect()
.当它是factor
时,如何计算该区域的y轴限制?矩形的x轴限制为-Inf
至Inf
.
I would like to add alternate shading area behind each bar to differentiate the factors in y axis. I know I can use geom_rect()
for this. How to calculate the y axis limits for the area, when it is a factor
? x axis limits for the rectangles would be -Inf
to Inf
.
我正在寻找与此图像相似的东西,但只寻找条形图而不是盒形图.
I am looking for something along the lines of this image, but for barplots instead of boxplots.
推荐答案
解决了
# 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)
这篇关于在ggplot2的条形图中为类别变量添加阴影替代区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!