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

如何用ggpubr的stat_cor将Pearson相关系数设为粗体显示?

解决stat_cor()设置相关系数粗体失效的问题

你遇到的问题是stat_cor()里直接加fontface = "bold"不生效,这是因为stat_cor()的参数列表里并没有fontface,这个参数属于底层的geom_text(),且分组显示时直接传递参数可能存在问题。以下是两种可靠的解决方法:

方法一:用表达式解析实现粗体

修改stat_cor()的label参数,把r.label用bold()函数包裹,同时开启parse = TRUE让ggplot解析表达式,以此实现粗体效果:

ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_point(aes(color = Species)) +
  stat_smooth(method = lm, aes(color = Species), se = FALSE) +
  stat_cor(aes(color = Species, label = after_stat(paste0("bold(", r.label, ")"))), 
           r.accuracy = 0.01, label.x = 4, label.y = c(8, 7.8, 7.6),
           parse = TRUE) +
  scale_color_manual(values = c("grey70", "gold", "green3")) +
  theme_classic() +
  theme(
    legend.background = element_rect(fill="grey90", 
                                     size=0.5, linetype="solid")
  )

方法二:显式指定geom并传递fontface

如果更习惯用fontface参数,可以显式指定geom = "text"并传递该参数,不过这种方式在部分分组渲染场景下可能出现问题,需要自行测试:

ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_point(aes(color = Species)) +
  stat_smooth(method = lm, aes(color = Species), se = FALSE) +
  stat_cor(aes(color = Species, label = after_stat(r.label)), 
           r.accuracy = 0.01, label.x = 4, label.y = c(8, 7.8, 7.6),
           geom = "text", fontface = "bold") +
  scale_color_manual(values = c("grey70", "gold", "green3")) +
  theme_classic() +
  theme(
    legend.background = element_rect(fill="grey90", 
                                     size=0.5, linetype="solid")
  )

两种方法中,方法一的表达式解析方式更稳定,尤其在多分组显示标签时,能确保所有标签都应用粗体样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 05:17:11