Home > Net >  How to create a grouped stacked bar chart, not facets
How to create a grouped stacked bar chart, not facets

Time:11-10

I am trying to create a stacked bar graph with ggplot in which my X axis shows month number and Y axis the total count of each species on each month. I'd like to create stacked bars showing monthly counts of species over the years, therefore I would have as many bars for a month as that month has been sampled over the years, note my data is unevenly distributed.

Sp<- data.frame(Species = c("A","A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","C","C","C","C","C","C","C","C","C","C","C","C","C","C","C","C","C","C","C","C","C","C"),
Month= c("2","3","4","4","4","7","3","4","4","5","6","4","5","6","6","7","4","3","4","5","6","7","3","4","4","5","6","4","5","6","4","5","6","2","2","8","5","5"),
Year= c("2018","2005","2006","2006","2006","2006","2008","2008","2008","2008","2018","2009","2009","2009","2018","2009","2009","2009","2009","2009","2018","2005","2005","2005","2006","2006","2005","2006","2005","2005","2005","2009","2009","2009","2018","2018","2018","2018"))

I am not too bothered about displaying the year but I would like the columns to be grouped from earlier to later month (Jan-Dec) on a single plot showing as many columns as a particular month has data for my entire time series. E.g., February would have 2 coluns, as there is data for February over 2 different years, whereas March would have 3 columns.

I have managed to create a plot using the below code, but it is displaying the results using year as a facet rather than grouping the stacked columns by repeated months on a single plot.

Sp%>% group_by(Month, Year, Species)%>%
 ggplot(aes(Month))    
  geom_bar(aes(fill= Species),stat='count') 
  facet_wrap( ~ Year, nrow = 1)

Outcome (from my real data rather than the dummy dataset I created above) Outcome

Expected Expected

Any help would be appreciated :)

Thanks!

CodePudding user response:

One option would be to switch Month and Year, i.e. to facet by Month. Also, you could use theme options to get rid of the facet look and I also opted for facet_grid to use space="free_x" argument so that the width of the panel is proportional to the number of bars per facet:

library(ggplot2)

ggplot(Sp, aes(Year))    
  geom_bar(aes(fill= Species), stat='count') 
  scale_y_continuous(expand = expansion(mult = c(0, .05)))  
  scale_x_discrete(expand = expansion(add = .8))  
  facet_grid(.~Month, switch = "x", space = "free_x", scales = "free_x")  
  theme_bw()  
  theme(strip.background.x = element_blank(), 
        strip.placement = "outside",
        axis.line = element_line(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        axis.ticks.length.x = unit(0, "pt"),
        panel.border = element_blank(),
        panel.spacing.x = unit(0, "pt"),
        panel.grid.major.x = element_blank())  
  labs(x = "Month", y = "Count")

enter image description here

  • Related