1

This question can be a continuation of Multi-row x-axis labels in ggplot line chart question.

I need to know how to label the strips. For example, in the link given, there are years mentioned on top of each plot such as 2009, 2010 and so on. If I need to display Year=2009, Year=2010 and so on, instead of 2009, 2010 etc. how should I change the code?

Sample code

set.seed(1)
df=data.frame(year=rep(2009:2013,each=4),
              quarter=rep(c("Q1","Q2","Q3","Q4"),5),
              sales=40:59+rnorm(20,sd=5))
library(ggplot2)
ggplot(df) +
  geom_line(aes(x=quarter,y=sales,group=year))+
  facet_wrap(.~year,strip.position = "top",scales="free")+
  theme(#panel.spacing = unit(0, "lines"),
    strip.placement = "outside",
    axis.title.x=element_blank(),
    legend.position="none") 
zephryl
  • 14,633
  • 3
  • 11
  • 30

1 Answers1

1

There are multiple ways to modify facet labels. You can modify your faceting variable in before plotting:

df$year <- paste0("Year=", df$Year)

ggplot(df) +
  ...

Or you can modify it within facet_wrap():

  ... +
  facet_wrap(
    .~paste0("Year=", year),
    strip.position = "top",
    scales = "free"
  ) +
  ...

Or you can specify a labeller function. This is definitely overkill for your case, but can be useful for transforming labels in more complex ways.

  ... +
  facet_wrap(
    .~year,
    labeller = as_labeller(\(x) paste0("Year=", x)),
    strip.position = "top",
    scales = "free"
  ) +
  ...

Output for all of these methods:

zephryl
  • 14,633
  • 3
  • 11
  • 30