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

如何修改ggpboxplot中stat_compare_means()输出的p值字体为Times New Roman?

如何将ggpubr中stat_compare_means()的p值字体设置为"Times New Roman"

你碰到的这个问题其实挺典型的——咱们用theme_bw(base_family = "Times New Roman")或者theme(text = element_text(family = "Times New Roman"))只能修改绘图的全局文本(比如坐标轴标签、图标题),但stat_compare_means()生成的p值标注属于独立的几何对象,全局theme设置管不到它,得单独指定字体参数才行。

给你两种可行的解决方案:

方法一:直接在stat_compare_means里指定字体

这是最直接的方式,通过text.args参数给p值文本传递字体族设置:

library(ggpubr)
library(ggplot2)
data("ToothGrowth")

# 先绘制基础箱线图
p <- ggboxplot(ToothGrowth, x = "supp", y = "len", 
               color = "supp", palette = "jco", 
               add = "jitter", facet.by = "dose", 
               short.panel.labs = FALSE)

# 添加p值标注并指定字体为Times New Roman
p + stat_compare_means(label = "p.format", 
                       text.args = list(family = "Times New Roman")) +
  theme_bw(base_family = "Times New Roman") # 同时设置全局字体保持风格统一

方法二:全局修改geom_text的默认字体

如果你希望所有geom_text(包括stat_compare_means生成的标注)都自动使用Times New Roman,可以提前修改ggplot的默认设置:

library(ggpubr)
library(ggplot2)

# 修改geom_text的默认字体
update_geom_defaults("text", list(family = "Times New Roman"))

# 再绘制箱线图和p值标注,此时p值会自动应用Times New Roman
data("ToothGrowth")
p <- ggboxplot(ToothGrowth, x = "supp", y = "len", 
               color = "supp", palette = "jco", 
               add = "jitter", facet.by = "dose", 
               short.panel.labs = FALSE)
p + stat_compare_means(label = "p.format") +
  theme_bw(base_family = "Times New Roman")

额外注意事项

如果你的R识别不到Times New Roman字体,可能需要先通过extrafont包导入系统里的字体:

library(extrafont)
font_import() # 首次运行会扫描系统字体,耗时较长
loadfonts() # 加载字体到R环境

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 08:57:37