r - Adding shading alternate areas for categorical variable in a bar plot in ggplot2 -
i trying t o plot bar plot using ggplot2
as follows:
library(ggplot2) ggplot(mtcars, aes(factor(carb))) + geom_bar() + coord_flip()
x axis continous variable, while y axis categorical 1 (factor
).
i add alternate shading area behind each bar differentiate factors in y axis. know can use geom_rect()
this. how calculate y axis limits area, when factor
? x axis limits rectangles -inf
inf
.
i looking along lines of image, barplots instead of boxplots.
solved it
# create data.frame shading info shading <- data.frame(min = seq(from = 0.5, = max(as.numeric(as.factor(mtcars$carb))), = 1), max = seq(from = 1.5, = max(as.numeric(as.factor(mtcars$carb))) + 0.5, = 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)
Comments
Post a Comment