r - R中ggplot2标签内的下标

标签 r ggplot2 facet-wrap subscript

这是这个问题的延续:Labeling facet strips in ggplot2

通过使用以下代码,我可以获得每个子图顶部的 Year = 2009、Year = 2010:

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") 

如果我需要有下标,我应该如何修改上述代码,例如,我需要显示 Year ab = 2009,而不是 Year = 2009

我尝试给予

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

但是失败了。

最佳答案

您可以尝试下标的 unicode 值,例如

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")

创建于 2022 年 11 月 30 日 reprex v2.0.2

这种方法是否有效将取决于您想要使用哪个下标字母,即有一个下标“a”(如上图所示),但我认为没有下标“b”。

关于r - R中ggplot2标签内的下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74622891/

相关文章:

R foreach : from single-machine to cluster

r - 使用 ggplot2 从动物园对象绘制多线图

r - 从 R 中的对角线逐行减去负矩阵元素

r - ggplot : why is automated text printed in legend's fill?

r - 控制每轴 ggplot2 裁剪

r - 更改构面标签的外观尺寸

r - 如何在 R 中将字符串解析为层次结构或树

r - ggplot2 在直方图中查找计数最大值

r - 使用 ggplot 和facet_wrap 从 0 开始 Y 轴

r - 在ggplot中向下移动刻面标签