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

R语言ggplot注释使用\u00B1、%+-%标注±符号失效问题求助

ggplot2文本标注±符号显示异常修复

失效原因

开启parse=TRUE时ggplot会调用R plotmath规则解析标签,原有写法失效的核心原因有三点:

  • %+-%是plotmath规则中的加减号运算符,被包裹在引号内时会被识别为普通文本,无法解析为±符号
  • R字符串中单个反斜杠为转义标识符,直接写\pm会因为不存在\p对应的转义规则直接抛出错误
  • 高版本ggplot2和部分图形设备对expression内部混杂的Unicode转义字符(\u00B1)兼容性下降,会出现符号渲染异常

解决方案

方案1:保留parse=TRUE,修正plotmath语法

不需要额外装包,只要把%+-%从引号中移出,作为表达式运算符直接书写即可:

# 无需用c()包裹expression,%+-%不放在引号内
avg1 <- expression(paste("22.2 ", %+-% , " 0.83"))
avg2 <- expression(paste("22.9 ", %+-% , " 0.67"))

如果习惯LaTeX语法,可安装latex2exp包做语法转换:

# install.packages("latex2exp")
library(latex2exp)
avg1 <- TeX("22.2 $\\pm$ 0.83")
avg2 <- TeX("22.9 $\\pm$ 0.67")

方案2:关闭parse参数,直接使用Unicode字符(兼容性最高)

不需要套用expression(),直接写入±字符,同时将annotate中的parse参数设为FALSE,不受plotmath语法限制,所有系统字体支持±的环境下都能正常渲染:

# 直接写文本即可,也可以用"\u00B1"替代±字符
avg1 <- "22.2 ± 0.83"
avg2 <- "22.9 ± 0.67"

# 调用annotate时修改parse参数
annotate(geom = "text", x = 21.85, y= 0.5, label= avg1, parse=FALSE, size=3, color = "aquamarine3")+
annotate(geom = "text", x = 22.55, y= 0.6, label= avg2, parse=FALSE, size=3, color = "firebrick4")

修正后完整代码

library(ggplot2)
avg1 <- "22.2 ± 0.83"
avg2 <- "22.9 ± 0.67"

density2 <- ggplot(Success_all, aes(x=Temp, fill = shape)) +
  # 高版本ggplot2建议用after_stat替代..xx..写法,避免废弃警告
  geom_density(aes(y=after_stat(density)),alpha=0.4) +
  annotate(geom = "text", x = 21.85, y= 0.5, label= avg1, parse=FALSE, size=3, color = "aquamarine3")+
  annotate(geom = "text", x = 22.55, y= 0.6, label= avg2, parse=FALSE, size=3, color = "firebrick4") +
  annotate(geom = "text", x = 20, y= 0.65, label= "(C)", size=4, fontface="bold") +
  theme_bw() +
  scale_fill_manual(values = c("firebrick4", "aquamarine3")) +
  scale_x_continuous(breaks = seq(20,25,0.5)) +
  theme(panel.grid =element_blank(), 
        legend.title = element_blank()) +
  xlab("Temperature (℃)") +
  ylab("Density") +
  geom_vline(xintercept = 22.86774, color = "firebrick4", linetype = 3) +
  geom_vline(xintercept = 22.17358, color = "aquamarine3", linetype = 3)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 15:57:51