在 ggplot2 中向 facet_wrap 添加下标和符号

Adding subscripts and symbols to facet_wrap in ggplot2

我正在尝试创建一些天气状况随时间变化的 2x2 分面图,但在向某些分面标题添加度数符号和上标时遇到问题。

weatherPLOT = data.frame(weather = rep(c("Soil Temperature (C)", 
                                        "Snow Depth (m)", 
                                        "Air Temperature (C)", 
                                        "Discharge (m3/sec)"), each = 366),
                           day = 1:366,
                           mean = 3, # Obvious place holders,
                           Lo95 = 2, # Are actual numbers in real code
                           Hi95 = 4)

ggplot(aes(y = mean, x = day), data = weatherPLOT) + 
  geom_ribbon(aes(ymin = Lo95, ymax = Hi95), alpha = 0.25) +
  geom_path(size = 1) + 
  theme(axis.title.y = element_blank()) + xlab("Julian Day") +
  facet_wrap( ~ weather, nrow = 2, ncol = 2, scales = "free")

我知道诀窍是在 facet_wrap 内部使用贴标机,但我无法让它工作 - 我只是想在 (C) 之前添加一个度数符号并使 3在 (m3/sec) 上标。

最简单的方法是将文本值本身更改为适当的符号,并使用 ggtext 包进行格式化。

\u00b0 是度数符号的 Unicode 值。 <sup>3</sup> 是上标 3 的 ggtext Markdown 代码。您使用 ggtext::element_markdown() 指定主题文本应为 markdown。

library(ggplot2)
weatherPLOT = data.frame(weather = rep(c("Soil Temperature (\u00b0C)", 
                                         "Snow Depth (m)", 
                                         "Air Temperature (\u00b0C)", 
                                         "Discharge (m<sup>3</sup>/sec)"), each = 366),
                         day = 1:366,
                         mean = 3, # Obvious place holders,
                         Lo95 = 2, # Are actual numbers in real code
                         Hi95 = 4)

ggplot(aes(y = mean, x = day), data = weatherPLOT) + 
  geom_ribbon(aes(ymin = Lo95, ymax = Hi95), alpha = 0.25) +
  geom_path(size = 1) + 
  labs(y = "", x = "Julian Day") +
  theme(strip.text = ggtext::element_markdown()) +
  facet_wrap( ~ weather, nrow = 2, ncol = 2, scales = "free")

reprex package (v2.0.0)

于 2021-08-25 创建

另一种方式如下:

weatherPLOT %>%
  mutate(weather = factor(weather,
                          labels = c(bquote('Air Temperature'*degree*C),
                                     "Discharge~(m^{3}/sec)",
                                     "Snow~Depth~(m)",
                                     bquote('Soil Temperature'*degree*C)))) %>% 
  ggplot(aes(y = mean, x = day)) + 
  geom_ribbon(aes(ymin = Lo95, ymax = Hi95), alpha = 0.25) +
  geom_path(size = 1) + 
  theme(axis.title.y = element_blank()) + xlab("Julian Day") +
  facet_wrap( ~ weather, nrow = 2, ncol = 2, scales = "free", labeller =  label_parsed)