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


i trying t o plot bar plot using ggplot2as follows:

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

enter image description here

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.

enter image description here

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) 

enter image description here


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -