ggplot: update facet labels with number of points in the plot

Viewed 200

I have a dataset data and could plot according to the requirenmts as below:

#Data
data <- data.frame(level = c(1,2,3,5,2,4,3,1,3), 
                   pay1 = c(10,21,32,12,41,21,36,14,17), 
                   pay2 = c(26,36,5,6,52,12,18,17,19))

#Plot
data %>% pivot_longer(-level) %>%
  ggplot(aes(x = name, y = value))+
  geom_boxplot() + 
  facet_wrap(~ level, scales = "free_x") +
  theme_bw()

enter image description here

I wish to update the facet labels according to the frequency of another variable level.

table(data$level)
# 1 2 3 4 5 
# 2 2 3 1 1 

How can the Facet labels be updated as 1 (n=2), 2 (n=2), 3 (n=3), 4 (n=1), 5 (n=1)??

1 Answers

I would just rename the factor levels with a mutate call that uses paste and n():

data %>% 
  pivot_longer(-level) %>%
  group_by(level, name) %>%
  mutate(level = paste0(level, " (n = ", n(), ")")) %>%
  ggplot(aes(x = name, y = value))+
  geom_boxplot() + 
  facet_wrap(~ level, scales = "free_x") +
  theme_bw()

enter image description here

Related