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

ggplot2箱线图如何控制stat_summary添加文本的字体与字号

问题原因

theme()中配置的text相关参数,仅能控制主题体系内的文本元素:包括坐标轴标签、刻度文本、图表标题、图例文本、分面标签等。所有通过geom_*()/stat_*()函数生成的几何对象类文本(比如你用stat_summary(geom="text")生成的样本量标签),不属于主题文本范畴,不会自动继承theme中的字体、字号设置,必须单独配置。

解决方法

方法1:单图层单独指定(推荐,仅影响当前标签)

直接在stat_summary()函数内传入family和size参数即可。

注意单位差异:element_text()的size单位是磅(pt),但geom_text()的size默认单位是毫米(mm),要和主题10号字大小一致,需要用ggplot内置常量.pt做换算,写为size = 10/.pt,直接写size=10会导致标签字远大于其他文本。

修改后的核心代码段:

stat_summary(fun.data = counts, geom = "text",
             family = "mono", # 匹配主题设置的等宽字体
             size = 10/.pt)   # 匹配主题设置的10号字大小

完整参考代码:

library("ggplot2")

v_min <- -1
v_max <- 3.5
increm <- 0.5
y_limits <- c(v_min, v_max)
increms <- seq(v_min, v_max, increm)


counts <- function(x){
  # 可调整adjust参数修改标签垂直位置
  adjust <- 0.95
  return(c(y = adjust * v_max, label = length(x))) 
  
}

ggplot(d1, aes(x = ONRC_Hierarchy, y=lwpMeanRut_inc)) +
    geom_boxplot(outlier.alpha = 0.2, outlier.size = 0.5) + 
    geom_hline(aes(yintercept=0), color="blue", linetype="dotted", linewidth=1)+
    stat_summary(fun.data = counts, geom = "text",
                 family = "mono",
                 size = 10/.pt) +
    scale_y_continuous(limits = y_limits, breaks = increms) + 
    xlab("") +
    ylab("Rut Increment (mm/year)\n") + 
    theme_minimal() + 
    theme(
          text = element_text(size = 10, family = "mono"),
          axis.text.x=element_text(angle = -35, hjust = 0),
          panel.grid.major.y = element_line(color = "lightgray",
                                        linewidth = 0.15,linetype = 2),
          panel.grid.minor.y = element_blank(),
          panel.grid.major.x = element_blank())

方法2:全局统一设置(适合图中有多组文本标签的场景)

如果你的图里有多处通过geom_text()/stat_summary()添加的文本,不需要每个图层重复传参,可以在绘图前修改文本几何对象的全局默认参数:

# 全局设置所有geom_text类元素的默认字体和字号
update_geom_defaults("text", list(
  family = "mono",
  size = 10/.pt
))

# 后续绘图代码不需要在stat_summary里单独加family和size参数,也会自动应用设置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 11:27:18