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

如何在ggplot2分面绘图的单个标签中使用特殊字符、上标或下标?

你可以通过自定义as_labeller()映射规则,仅修改指定分面的标签,其余分面保持原名称即可,实现代码如下:

library(ggplot2)
library(dplyr)
library(hrbrthemes)

conc <- runif(nrow(iris), min = 5, max = 10)
df <- iris %>% mutate(mass_area = conc/Petal.Length*Sepal.Length)

melted <- reshape2::melt(df)

# 自定义分面标签映射
facet_labs <- c(
  Sepal.Length = "Sepal.Length",
  Sepal.Width = "Sepal.Width",
  Petal.Length = "Petal.Length",
  Petal.Width = "Petal.Width",
  Species = "Species",
  mass_area = expression("Chl concentration" ~ (mu ~ g ~ " " ~ cm^{-2}))
)

bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) + 
  geom_boxplot() +
  theme_ipsum() +
  scale_fill_brewer(palette = "Greens") +
  theme(
    legend.position = "bottom",
    plot.title = element_text(size = 10)) +
  theme(axis.text.x = element_blank(),
        strip.text = element_text(size = 12)) +
  # 请替换为实际标题值,避免运行报错
  ggtitle("自定义标题") +
  xlab("") +
  ylab("") +
  # 新增labeller参数解析自定义标签
  facet_wrap(~variable, scale = "free", labeller = labeller(variable = as_labeller(facet_labs, default = label_parsed)))
bp1

核心逻辑说明

  • 构造命名向量facet_labs时,仅修改需要特殊格式的mass_area对应的取值,其余变量直接保留原名称即可
  • as_labeller()的default = label_parsed参数会自动解析表达式格式的标签,实现上标、希腊字母等特殊格式的渲染
  • 若你的数据集variable列取值和示例不同,只需调整facet_labs的命名键和实际变量名对应即可,后续新增分面变量也只需补充对应键值对

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:51:02