Grouped bar plot column width uneven due to no data

后端 未结 2 972
孤街浪徒
孤街浪徒 2021-01-24 00:29

I am trying to display a grouped bar plot for my dataset, however, due to some months have no data (no income), the column width is showing up as unequal and I was hoping to hav

相关标签:
2条回答
  • 2021-01-24 00:58

    There are two ways that this can be done.

    1. If you are using the latest version of ggplot2(from 2.2.1 I believe), there is a parameter called preserve in the function position_dodge which preserves the vertical position and adjust only the horizontal position. Here is the code for it.

    Code:

    import(ggplot2)
    plot = ggplot(Checkouts, aes(fill=Checkouts$State, x=Checkouts$Month, y=Checkouts$Income)) + 
    geom_bar(colour = "black", stat = "identity", position = position_dodge(preserve = 'single'))
    
    1. Another way is to precompute and add dummy rows for each of the missing. using table is the best solution.
    0 讨论(0)
  • 2021-01-24 01:18

    You are looking for position_dodge2(preserve = "single")(https://ggplot2.tidyverse.org/reference/position_dodge.html).

    library(ggplot2)
    plot = ggplot(Checkouts, aes(fill = State, x = Month, y= Income)) + 
      geom_bar(colour = "black", stat = "identity", 
               position = position_dodge2(preserve = "single")) 
    

    Also, you don't need to specify the columns to the data frame with $ in ggplot(). For example, Checkouts$State can be replaced with State.

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