ggplot: Modify breaks and labels using facet_wrap

The example below modifies the breaks and labels, however, for only one category. How could I achieve the same i.e. place n() beneath the years using facet_wrap(~ delay_type)?

In addition, how do I add sd() beside or below n()?

library(tidyverse)
###########
# Data
###########
set.seed(123)
toy_data <- tibble(
  year = rep(2008:2017, times = 2),
  delay_type = rep(c("A", "B"),each = 10),
  mean = rnorm(20, mean = 50 , sd = 20),
  median = rnorm(20, mean = 40, sd = 15)
) %>% 
  pivot_longer(
    cols = mean:median,
    names_to = "stats",
    values_to = "delay"
  ) %>% 
 mutate(number_obs = rep(100:109, each = 4),
         sd = rep(1:10, each = 2, times = 2)) #updated sd

######################
# Sample Plot
######################
# x-axis breaks and labels
x <- toy_data %>%
  filter(delay_type == "A") %>% 
  arrange(year) %>% 
  distinct(breaks=year, labs=paste0(year, " (n=",number_obs,")"))
# Plot
toy_data %>% 
  filter(delay_type == "A") %>% 
  ggplot(aes(x = year, y = delay , color = stats)) +
  geom_line(size=0.3, alpha=0.5) +
  geom_text(aes(label=round(delay)), show.legend=FALSE, size=2.8) +
  labs(
    subtitle = "Yearly Stat",
    color = "Statistics",
    y = "Delay",
    x = "Year"
  ) +
  # Breaks and Labels
  scale_x_continuous(breaks = x$breaks, labels=str_wrap(x$labs,5)) +
  theme_bw() +
  theme(text = element_text(size = 9)) +
  guides(colour=guide_legend(override.aes=list(size=2, alpha=1)))

Created on 2020-11-20 by the reprex package (v0.3.0)

I dont think you can make facet_wrap place different fixed/arbitrary labels on an axis...
I would switch out facet_wrap for a cowplot (library) approach where individual charts are constructed and use cowplot to compose them as facets.

but unlike the single n per delay type per year, there is no single sd , there is one each for mean and median.
Do you want both, or only one ? Technically its just a case of prepping the data and adding to your labs=paste0... but deciding what is appropriate requires context.

I made a mistake in creating the toy_data. Please replace replace sd = rep(1:10, each = 2, times = 2). Now it is similar to the n. Thanks!

Thanks for your response. Ignoring the facet_wrap, could you please help me placing the sd beside or below the n? Thanks!

%>% 
  distinct(breaks=year, labs=paste0(year, " (n=",number_obs,")\n(sd=",sd,")"))

or

library(glue)
...
%>% 
distinct(breaks=year, labs=glue("{year}
                                  (n={number_obs})
                                  (sd={sd})"))
1 Like

Just whatI wanted :smile: Thanks!