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

如何在R ggplot图例中设置字母x的数学字体(如𝒙₀)

在ggplot图例中显示数学风格的𝒙₀

方法一:直接使用Unicode数学斜体字符

Unicode包含专门的数学风格斜体字母,其中数学斜体x的字符为𝒙(编码U+1D499),可以直接在图例标签中使用,搭配下标0即可得到目标样式的𝒙₀。

示例代码:

library(ggplot2)

ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
  geom_point() +
  scale_color_discrete(labels = c("𝒙₀", "组1", "组2"))

方法二:用ggtext包实现富文本样式控制

借助ggtext包,可在ggplot文本元素中使用markdown/HTML语法,指定数学字体来渲染字母x,实现标准数学风格效果。

示例代码:

library(ggplot2)
library(ggtext)

ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
  geom_point() +
  scale_color_discrete(labels = c("<span style='font-family: \"STIX Two Math\", \"Latin Modern Math\";'>x₀</span>", "组1", "组2")) +
  theme(legend.text = element_markdown())

注:需确保系统安装了STIX Two Math、Latin Modern Math这类专业数学字体。

方法三:结合plotmath与数学字体

若偏好使用plotmath语法,可通过指定绘图设备的数学字体,让plotmath渲染出符合要求的字母样式。

示例代码:

library(ggplot2)

# 根据系统设置对应字体
# Windows系统
windowsFonts(Math = windowsFont("STIX Two Math"))
# macOS系统
# quartzFonts(Math = quartzFont("STIX Two Math"))

ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
  geom_point() +
  scale_color_discrete(labels = expression(italic(x)[0], group1, group2)) +
  theme(text = element_text(family = "Math"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 12:29:52