How label min and max values per group in ggplot?

Viewed 656

I have a dataset that counts number of posts per month per year. Looks like that:

   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 as a date is needed only for rendering month names in ggplot).

So the resulting plot is generated like that:


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

and looks like that:

plot per month

I want to give year labels for topmost and bottom most outliers, so for each month it can be seen which year produced the least and the most posts per month. What is the efficient way to do it?

1 Answers

Ok, I found the solution. Pretty simple:


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


and the resulting plot is: resulting plot

Related