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

如何在ggplot的stat_summary文本中实现下标(将Q1改为Q₁)

解决ggplot箱线图stat_summary中Q₁无法正常显示的问题

方法1:用表达式解析实现下标(最稳妥)

stat_summary的文本渲染支持表达式解析,只要在自定义函数里返回带下标表达式的对象,再开启parse = TRUE就能正常显示Q₁。示例代码:

library(ggplot2)

# 自定义统计函数,返回带Q₁下标和数值的表达式
get_q1_text <- function(x) {
  q1_val <- round(quantile(x, 0.25), 2)
  # bquote可以把计算值嵌入表达式
  bquote(Q[1] == .(q1_val))
}

# 绘图时开启表达式解析
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
  geom_boxplot() +
  stat_summary(
    fun.data = function(x) data.frame(y = max(mpg) + 1, label = get_q1_text(x)),
    geom = "text",
    parse = TRUE  # 关键:让ggplot解析表达式下标
  )

方法2:用ggtext支持Markdown格式

如果习惯用Markdown的<sub>标签写下标,可借助ggtext包的富文本渲染功能:

library(ggplot2)
library(ggtext)

# 生成带Markdown下标的文本
get_q1_md <- function(x) {
  q1_val <- round(quantile(x, 0.25), 2)
  paste0("Q<sub>1</sub> = ", q1_val)
}

ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
  geom_boxplot() +
  stat_summary(
    fun.data = function(x) data.frame(y = max(mpg) + 1, label = get_q1_md(x)),
    geom = "richtext",
    parse_markdown = TRUE,
    fill = NA,  # 去掉背景框
    label.color = NA  # 去掉边框
  )

方法3:修复Unicode显示的字体问题

如果Unicode的Q₁显示为空方块,是因为当前绘图字体不支持该字符,指定支持Unicode的字体即可:

library(ggplot2)

get_q1_unicode <- function(x) {
  q1_val <- round(quantile(x, 0.25), 2)
  paste0("Q₁ = ", q1_val)
}

# 不同系统选对应字体:Windows用"Segoe UI",Mac用"SF Pro Text",Linux用"Noto Sans"
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
  geom_boxplot() +
  stat_summary(
    fun.data = function(x) data.frame(y = max(mpg) + 1, label = get_q1_unicode(x)),
    geom = "text",
    family = "Segoe UI"
  ) +
  theme(text = element_text(family = "Segoe UI"))  # 全局统一字体

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:55:16