【问题标题】:How label min and max values per group in ggplot?如何在ggplot中标记每组的最小值和最大值?
【发布时间】:2020-12-31 10:11:53
【问题描述】:

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

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

看起来像这样:

我想为最顶部和最底部的异常值提供年份标签,因此每个月都可以看到哪个年份每月产生的帖子最少和最多。什么是有效的方法?

【问题讨论】:

    标签: r ggplot2 dplyr


    【解决方案1】:

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

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

    结果图是:

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      相关资源
      最近更新 更多