如何将总和标记为来自连续条形值的 y 轴列值的总和,如示例中每个 x 轴“日期”的“确认”案例

How do I label the sum the total of y-axis column values from consecutive bar values like in the example “Confirmed” Cases per x-axis “Date”

我已经为此工作了一段时间,现在重新发布这篇文章,希望能简化问题的定义,并从我之前尝试的反馈中获得一些清晰度。我能够标记每个单独的列值,但无法将代码放在一起以求和。我看过的例子从来没有按照我尝试将它们放在一起的方式工作,例如 goup_by 或总结等。我只想对“已确认案例”的值求和,而不显示其他与许多 c("x", "Y", ... "data") 一样,列值变得无法读取。

这是数据框:

dput(COVID1[1:12, ])
structure(list(COUNTY = c("Antrim", "Antrim", "Antrim", "Charlevoix", 
  "Charlevoix", "Grand Traverse", "Grand Traverse", "Grand Traverse", 
  "Antrim", "Grand Traverse", "Grand Traverse", "Grand Traverse"
  ), Date = structure(c(18453, 18456, 18457, 18453, 18455, 18453, 
  18456, 18457, 18455, 18453, 18456, 18457), class = "Date"), CASE_STATUS = c("Confirmed", 
  "Confirmed", "Confirmed", "Confirmed", "Confirmed", "Confirmed", 
  "Confirmed", "Confirmed", "Probable", "Probable", "Probable", 
  "Probable"), Cases = c(1L, 1L, 2L, 1L, 3L, 2L, 2L, 1L, 1L, 1L, 
  1L, 1L)), row.names = c(NA, 12L), class = "data.frame")

代码:

        ggplot(filter(COVID1, COUNTY %in% c("Antrim", "Charlevoix", "Grand Traverse"), Cases > 0)) +
            geom_col(aes(x = Date, y = Cases, fill = CASE_STATUS), position = position_stack(reverse = TRUE), width = .88)+
            geom_text(aes(x = Date, y = Cases, label = (Cases)), position = position_stack(reverse = TRUE), vjust = 1.5, size = 3, color = "white") +
            scale_fill_manual(values = c('blue',"tomato"))+
            scale_x_date(labels = date_format("%m/%d"), limits = as.Date(c('2020-07-09','today()')), breaks = "1 week")+
    theme(axis.text.x = element_text(angle=0))+
labs(title = "Antrim - Grand Traverse - Charlevoix")

我不确定我是否理解问题,但我想你想添加已确认病例的总和作为标签。可能有一种 ggplot 方法可以做到这一点,但我认为最直接的方法是用你的标签制作另一个数据集并将其输入。

date_labels <- filter(COVID1, COUNTY %in% c("Antrim", "Charlevoix", "Grand Traverse"), Cases > 0) %>% group_by(Date) %>% summarise(confirmed_cases = sum(Cases[CASE_STATUS == "Confirmed"]))

ggplot(filter(COVID1, COUNTY %in% c("Antrim", "Charlevoix", "Grand Traverse"), Cases > 0)) +
  geom_col(aes(x = Date, y = Cases, fill = CASE_STATUS), position = position_stack(reverse = TRUE), width = .88)+
  geom_text(data = date_labels, aes(x = Date, y = 1, label = confirmed_cases), position = position_stack(reverse = TRUE), vjust = 1.5, size = 3, color = "white") +
  scale_fill_manual(values = c('blue',"tomato"))+
  scale_x_date(labels = label_date("%m/%d"), limits = as.Date(c('2020-07-09','today()')), breaks = "1 week")+
  theme(axis.text.x = element_text(angle=0))+
  labs(title = "Antrim - Grand Traverse - Charlevoix")

给我这个结果: