You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2的facet_wrap分面标题中添加下标、度符号及上标特殊字符

解决方法

方案1:修改原始数据的分类标签,配合label_parsed渲染

首先将weather字段的取值替换为符合R plotmath语法的字符串,再在facet_wrap中指定labeller参数即可:

library(ggplot2)
# 修改weather的取值为plotmath可解析的格式
weatherPLOT = data.frame(weather = rep(c("Soil~Temperature~(degree*C)", 
                                        "Snow~Depth~(m)", 
                                        "Air~Temperature~(degree*C)", 
                                        "Discharge~(m^3/sec)"), each = 366),
                           day = 1:366,
                           mean = 3,
                           Lo95 = 2,
                           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") +
  # 增加labeller参数,用label_parsed解析标签
  facet_wrap( ~ weather, nrow = 2, ncol = 2, scales = "free",
              labeller = labeller(weather = label_parsed))

方案2:不修改原始数据,自定义labeller映射

如果不想改动原始数据框的内容,可以单独定义标签映射规则:

library(ggplot2)
library(dplyr) # 用到case_when做匹配,也可以用base R的ifelse替换

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,
                           Lo95 = 2,
                           Hi95 = 4)

# 自定义标签转换函数
weather_labeller <- function(val) {
  case_when(
    val == "Soil Temperature (C)" ~ "Soil~Temperature~(degree*C)",
    val == "Snow Depth (m)" ~ "Snow~Depth~(m)",
    val == "Air Temperature (C)" ~ "Air~Temperature~(degree*C)",
    val == "Discharge (m3/sec)" ~ "Discharge~(m^3/sec)"
  )
}

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",
              labeller = labeller(weather = as_labeller(weather_labeller, default = label_parsed)))

关键语法说明

  • plotmath表达式中:degree对应度符号,^后接的内容会渲染为上标,~代表空格,*用于连接两个不需要空格的符号
  • label_parsed会将传入的字符串解析为plotmath表达式,自动渲染为对应的数学符号格式

内容的提问来源于stack exchange,提问作者ZombiePlan37

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 05:42:02