每天使用 ggplot2 堆叠直方图

Stacked Histogram per day with ggplot2

我的数据在这里 googledoc

看起来像这样:

# 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

我想创建一个包含每日 bin 的堆叠直方图,如图中所示。

其中:n_sym 和 n_rep 是相互叠加的计数。

我不明白如何进行....

您可以通过这种方式进行修改以实现您想要的情节:

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))