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

前端 未结 2 621
渐次进展
渐次进展 2021-01-21 18:26

I am trying t o plot a bar plot using ggplot2as follows:

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


        
相关标签:
2条回答
  • 2021-01-21 18:31

    Perhaps something along these lines where you overlay the wider shaded bars, which vary in color, with the darker smaller bar?

    ggplot(mtcars, aes(factor(carb))) +
      geom_bar(width = 1.1, aes(x = factor(carb), fill = ifelse(mtcars$carb %in% c(1,3,6), "blue", "transparent"))) +
      guides(fill = FALSE) +
      geom_bar(width = 0.7) +
      scale_fill_manual(values = c("transparent", "blue")) +
      coord_flip()
    

    0 讨论(0)
  • 2021-01-21 18:45

    Solved it

    # 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)
    

    0 讨论(0)
提交回复
热议问题