简体   繁体   中英

Subscript within labeller in ggplot2 in R

This is a continuation of this question: Labeling facet strips in ggplot2

By using the following code, I can obtain Year = 2009, Year = 2010 to the top of each sub plot:

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,
    labeller = as_labeller(\(x) paste0("Year=", x)),
    strip.position = "top",
    scales = "free") +
  theme(#panel.spacing = unit(0, "lines"),
    strip.placement = "outside",
    axis.title.x=element_blank(),
    legend.position="none") 

How should I modify the aforementioned code if I need to have a subscript, let's say for example, instead of Year = 2009, I need to display Year a b = 2009

I tried giving

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

but it failed.

You could try the unicode value for the subscript, eg

library(tidyverse)
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))

ggplot(df) +
  geom_line(aes(x=quarter,y=sales,group=year))+
  facet_wrap(
    .~year,
    labeller = as_labeller(\(x) paste0("Year a\u2090 = ", x)),
    strip.position = "top",
    scales = "free") +
  theme(#panel.spacing = unit(0, "lines"),
    strip.placement = "outside",
    axis.title.x=element_blank(),
    legend.position="none")

Created on 2022-11-30 with reprex v2.0.2

Whether or not this approach will work will depend on which subscript letters you want to use, ie there's a subscript "a" (shown in the plot above) but I don't think there is a subscript "b".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM