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

ggplot中如何修改sjPlot生成的标注数据标签字体?

修改sjPlot生成的数据标签字体
  • 问题根源:sjPlot通过show.values = TRUE添加的数值标签属于geom_text独立图层,这类图层的字体不受ggplot主题theme(text = ...)控制,需要单独调整。
  • 解决方案:遍历绘图对象的图层,定位文本类图层并修改其字体参数,具体实现代码如下:
# 定义所需字体(保留你的原有代码)
windowsFonts(A = windowsFont("Times New Roman"), B = windowsFont("Century Gothic"))

# 生成sjPlot绘图对象(保留你的原有代码)
a <- plot_model(sl_distr_model,
                order.terms = c(1,2,3,4,5,6,7),
                show.values = TRUE,
                value.offset = .3,
                rm.terms = c("taxon_detailAnas platyrhynchos","taxon_detailAnas strepera","logshape","logshape:cadencefactor1h","logshape:cadencefactor2h","logshape:cadencefactor3h","logshape:cadencefactor6h","logshape:cadencefactor12h","logshape:cadencefactor24h"),
                axis.lim = c(xlimrange_min,xlimrange_max),
                colors = c("firebrick"),
                wrap.labels = 60,
                title = "Plot 3: Intercept parameters by time interval - Relationship bewtween shape and scale gamma parameters of step length distributions 7.429",
                axis.title = "Intercept = Red; Ratio of Shape to Rate parameters = Blue")

# 遍历图层,修改数据标签字体
for (i in seq_along(a$layers)) {
  # 识别geom_text类型的图层
  if (inherits(a$layers[[i]]$geom, "GeomText")) {
    # 应用预设字体家族
    a$layers[[i]]$aes_params$family <- "A"
  }
}

# 应用主题字体设置并输出最终图表
final_plot <- a + theme(text = element_text(family = "A"))
print(final_plot)
  • 补充说明:若你的sjPlot版本使用geom_label生成标签,只需将代码中的GeomText替换为GeomLabel即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:02:19