r - 如何在ggplot中标记每组的最小值和最大值?

标签 r ggplot2 dplyr

我有一个数据集,可以计算每年每月的帖子数量。看起来像这样:

   monthdate   year     n
   <date>     <dbl> <int>
 1 2020-01-01  2001   133
 2 2020-01-01  2002   129
 3 2020-01-01  2003   149
 4 2020-01-01  2004    96
 5 2020-01-01  2005    94
 6 2020-01-01  2006   109
 7 2020-01-01  2007   158
 8 2020-01-01  2008   138
 9 2020-01-01  2009    83

(monthdate,因为仅在 ggplot 中渲染月份名称时才需要日期)。

所以结果图是这样生成的:


posts %>% mutate(monthdate = as.Date(paste("2020", month, '01', sep = "-"))) %>%
  group_by(monthdate, year) %>% summarise(n = n()) %>%
  ggplot(aes(x = monthdate, y = n)) +
  geom_point(, stat = 'identity') +
  geom_smooth(method = "loess") +
  scale_x_date(date_breaks = "1 month", date_labels = "%b") 

看起来像这样:

plot per month

我想为最上面和最下面的异常值提供年份标签,这样每个月就可以看到哪一年每月产生的帖子最少和最多。有效的方法是什么?

最佳答案

好的,我找到了解决方案。很简单:


posts %>% mutate(monthdate = as.Date(paste("2020", month, '01', sep = "-"))) %>%
  group_by(monthdate, year) %>% summarise(n = n()) %>% group_by(monthdate) %>% mutate(lab=case_when(n==max(n)|n==min(n)~year))%>%
  ggplot(aes(x = monthdate, y = n)) +
  geom_point(, stat = 'identity') +
  geom_smooth(method = "loess") +
  scale_x_date(date_breaks = "1 month", date_labels = "%b") +
  xlab('Month')+
  ylab('Number of posts')+ geom_text(aes(label=lab))


结果图是: resulting plot

关于r - 如何在ggplot中标记每组的最小值和最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65519449/

相关文章:

r - dplyr 为每个类别选择前 10 个值

r - 无法从 Rstudio 服务器授权 Google 表格

Python 与 R 的 fromJSON()、unlist()、attr() 等价的函数?

r - 向 ggplot 图形添加文件名或其他注释

r - facet_wrap的百分比直方图

r - 有什么方法可以使 R 中散点图中的绘图点更加透明吗?

r - 制作ggplot线图,其中线遵循行顺序

r - 使用 dplyr 语法和 attr 函数转换时区

r - 如何并行地向两个地 block 添加点? (在R)

r - R 中的增量时间戳解析(纳秒、微秒、毫秒)