Stacked barchart in ggplot2 with months and counts

35 Views Asked by At

I thought this would be simple, but I also haven't used ggplot2 a whole lot, so here I am. This is a portion of my dataset:

Month     Cause
1    Oct  Unknown 
2    Apr   Unknown
3    Nov  Roadkill
4    Oct   Disease
5    Sep Predation
6    Jul   Disease
7    Aug Predation
8    Oct   Disease
9    May  Roadkill
10   Feb Predation
11   Dec Predation
12   Feb Predation
13   Nov   Unknown
14   Nov   Hunting
15   Nov   Unknown
16   May   Unknown
17   Jan   Unknown
18   Apr   Unknown
19   Sep   Disease
20   Sep   Disease
21   Dec   Unknown
22   Aug   Disease
23   Jul Predation
24   Sep   Disease
25   Jun Predation
26   Apr Predation
27   Jun   Unknown
28   Jan   Unknown
29   Nov   Disease
30   Aug   Disease
31   Oct   Hunting

What I want is a stacked barchart with Month on the x axis (including March, which does not have any Causes) from Jan - Dec and then for each month, the causes stacked by count (y axis). I guess I assumed R could do the counting and sorting for me if I knew the code (which is probably still the case), but I haven't been able to find the code I need online. Any thoughts?

1

There are 1 best solutions below

2
TarJae On

Something like this:

library(tidyverse)
library(lubridate)
df %>% 
  count(Month, Cause) %>% 
  mutate(Month = dmy(paste("01", Month, "2000", sep = "-"))) %>% 
  ggplot(aes(x = Month, y=n, fill=Cause))+
  geom_col(position = position_fill()) +
  geom_text(aes(label =  n),
            position = position_fill(vjust = .5)) +
  scale_x_date(date_labels = "%b", date_breaks = '1 month')+
  theme_bw()

enter image description here