Home > Enterprise >  How do I label the maximum metric in a faceted ggplot?
How do I label the maximum metric in a faceted ggplot?

Time:08-07

I would like to place at the top of the largest column the x value (goals). So Team A would have the label "3" and Team B the label "2" on top of those respective columns. faceted ggplot

Code:

df <- tibble ( team = rep(c('A', 'B'), each = 5),
               goals = rep(1:5,2),
               prob = c(.10, .15, .25, .20, .15, .20, .30, .20, .10, .05))

df %>% 
  ggplot(aes(x = goals, y = prob))  
  geom_col()  
  facet_wrap(~team)

CodePudding user response:

One option would be to make a separate data frame containing the "top" observations per team using e.g. group_by slice_max. Afterwards you could pass this dataset to geom_text to add the labels for just the top observations:

df <- data.frame( team = rep(c('A', 'B'), each = 5),
               goals = rep(1:5,2),
               prob = c(.10, .15, .25, .20, .15, .20, .30, .20, .10, .05))

library(ggplot2)
library(dplyr, warn = FALSE)

df_lab <- df |> 
  group_by(team) |> 
  slice_max(prob, n = 1) |> 
  ungroup()

ggplot(df, aes(x = goals, y = prob))  
  geom_col()  
  geom_text(data = df_lab, aes(label = goals), vjust = 0, nudge_y = .005)  
  facet_wrap(~team)

CodePudding user response:

Another option if you want to do it all in a single pipe would be:

df %>% 
  group_by(team) %>%
  mutate(label = ifelse(prob == max(prob), goals, "")) %>%
  ggplot(aes(x = goals, y = prob))  
  geom_col()  
  facet_wrap(~team)  
  geom_text(aes(label = label), vjust = -0.5)

enter image description here

  • Related