Stacked Histogram per day with ggplot2

Viewed 66

I have my data here in this googledoc

That looks like this:

# A tibble: 57 × 3
   date       n_sym n_rep
   <date>     <dbl> <dbl>
 1 2020-06-01   153    63
 2 2020-06-02   206   168
 3 2020-06-03   192   202
 4 2020-06-04   168   247
 5 2020-06-05   155   211
 6 2020-06-06   150   155
 7 2020-06-07   100    85
 8 2020-06-08   192   125
 9 2020-06-09   182   195
10 2020-06-10   198   234
# … with 47 more rows

I would like to create a stacked histogram with daily bins, like something in this figure.

Where: n_sym and n_rep are counts stacked one over each other.

I can't understand how to proceed....

enter image description here

1 Answers

This way you could modify to achieve your desired plot:

library(tidyverse)
library(scales)

df1 <- df %>%  
  pivot_longer(
    -date
  ) %>%
  mutate(date = as.Date(date), 
         name = ifelse(name=="n_sym", "Onset of symptoms", "Date of reporting"))

ggplot(df1, aes(x=date, y=value, fill=name))+
  geom_col()+
  xlab("Onset of symptoms, alternatively date of reporting (2020)") + 
  ylab("Number of reported cases") + 
  scale_fill_manual(values = c("#ffc000", "#045aa0"))+
  scale_x_date(date_breaks = "1 day", labels = date_format("%d/%m")) +
  scale_y_continuous(expand = c(0, 0), limits = c(0, max(df1$value)),
                     breaks=seq(0,max(df1$value),100))+
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))+
  theme(legend.position="bottom")+
  guides(fill=guide_legend(title=""))+
  coord_fixed(ratio = .05)+
  theme(axis.title = element_text(size = 16))  

enter image description here

Related