You need to enable JavaScript to run this app. 如何在ggplot中使geom_text与stat_cor字体保持一致
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot中使geom_text与stat_cor字体保持一致

统一geom_text与stat_cor文本样式的实现方案

样式差异的核心原因

stat_cor是基于ggplot2::geom_text的封装函数,两者出现字体观感差异,本质是参数设置不匹配,而非字体种类的本质区别。stat_cor内置的默认文本设置为:

  • 字体族为系统默认无衬线字体"sans"
  • 字重为常规样式"plain",无加粗、斜体效果
  • 文本左对齐,无额外描边、阴影或背景效果
  • 大小参数单位与原生geom_text完全一致

你之前使用geom_text时,未显式对齐上述默认参数,同时设置了和stat_cor不一致的size值,最终导致观感差异。

逐参数对齐调整方法

只需在geom_text调用中补充和stat_cor完全一致的参数即可消除差异:

  • 统一文本大小:将geom_text的size参数设置为和stat_cor相同的数值(示例中为4)
  • 显式指定字体参数:补充family = "sans"、fontface = "plain",避免绘图设备自动 fallback 到其他字体
  • 对齐文本逻辑:补充hjust = 0匹配stat_cor的左对齐规则
  • 显式指定文本颜色为"black",避免全局主题继承波动带来的色差

修正后的完整可运行代码

library(ggplot2)
library(ggpubr)

# 读取示例数据集
beer <- read.csv("http://users.stat.umn.edu/~helwig/notes/MNbeer.csv")

# 拟合线性模型,自动提取斜率与对应标准误
fit_model <- lm(IBU ~ ABV, data = beer)
model_summary <- summary(fit_model)
slope_val <- coef(fit_model)[2]
slope_se_val <- model_summary$coefficients[2, 2]
slope_text <- paste0("Slope = ", round(slope_val, 2), " ± ", round(slope_se_val, 2))

# 绘制图形
ggplot(data = beer, aes(x = ABV, y = IBU)) +
  stat_smooth(method = "lm") +
  geom_point() +
  # 与stat_cor样式完全对齐的斜率标注
  geom_text(
    x = 4.45, y = 88,
    label = slope_text,
    size = 4,
    family = "sans",
    fontface = "plain",
    hjust = 0,
    color = "black"
  ) +
  theme_bw() +
  theme(
    panel.grid = element_blank(),
    text = element_text(size = 14, color = "black"),
    axis.text.x = element_text(size = 14, color = "black"),
    axis.text.y = element_text(size = 14, color = "black")
  ) +
  stat_cor(
    aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~")),
    label.x = 4, size = 4
  )

更彻底的统一方案

如果想100%保证样式无差异,可以不需要单独调用geom_text,直接将斜率、标准误、R²、p值的内容拼接成统一的标签字符串,通过stat_cor一次性渲染,从根源上避免两套渲染逻辑的差异:

# 拼接所有需要展示的统计内容(使用plotmath语法匹配stat_cor的解析规则)
full_stat_label <- paste0(
  "R^2~`=`~", round(model_summary$r.squared, 2), "~`,`~",
  "p~`=`~", format.pval(model_summary$coefficients[2,4], digits = 3), "~`,`~",
  "Slope~`=`~", round(slope_val, 2), "~`±`~", round(slope_se_val, 2)
)

ggplot(data = beer, aes(x = ABV, y = IBU)) +
  stat_smooth(method = "lm") +
  geom_point() +
  theme_bw() +
  theme(
    panel.grid = element_blank(),
    text = element_text(size = 14, color = "black"),
    axis.text.x = element_text(size = 14, color = "black"),
    axis.text.y = element_text(size = 14, color = "black")
  ) +
  # 所有统计标注均由stat_cor渲染,样式天然统一
  stat_cor(
    label.x = 4, size = 4,
    label = full_stat_label
  )

注意:如果需要在标签中添加数学符号、上标等特殊格式,保持标签的plotmath语法和stat_cor的默认解析规则一致即可,不需要额外调整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 17:15:06