control hierarchy of position_dodge

后端 未结 1 1960
抹茶落季
抹茶落季 2021-01-22 12:33

Is there a way to control which element is plotted in front of the other if one uses dodged bar charts.

 ggplot(mtcars, aes(x=factor(cyl), fill=factor(vs))) +
           


        
相关标签:
1条回答
  • 2021-01-22 12:56

    Your control here is limited. Using factor levels we can control i) the fill color ordering and ii) the ordering of position_dodge using group.

    Here are the four options:

    p1 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 0:1), group = factor(vs, 0:1))) +
      geom_bar(position = position_dodge(width = - 0.5))
    
    p2 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 0:1), group = factor(vs, 1:0))) +
      geom_bar(position = position_dodge(width = - 0.5))
    
    p3 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 1:0), group = factor(vs, 0:1))) +
      geom_bar(position = position_dodge(width = - 0.5))
    
    p4 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs, 1:0), group = factor(vs, 1:0))) +
      geom_bar(position = position_dodge(width = - 0.5))
    
    library(cowplot)
    plot_grid(p1, p2, p3, p4, align = 'hv')
    

    So it seems only the dodging order is important. In the dev version at least, the right bar is always plotted in front of the left bar.

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