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

如何统一ggplot中公式系数的小数位数?修改指定系数为1位小数

解决ggplot中回归公式小数位数不一致的问题

问题原因

你当前使用的coef.digits = 4控制的是有效数字位数,而非小数位数。当系数的整数部分位数不同时,就会出现小数位数不一致的情况——比如59.23是四位有效数字,154.3也是四位有效数字,但二者的小数位数不同。

解决方案

通过自定义回归等式标签,直接指定系数的小数位数,确保所有系数统一显示一位小数:

library(ggplot2)
library(ggpmisc)

ggplot(df, aes(x = FTSWt, y = SLA, group = Year)) +
  geom_point(aes(color = as.factor(Year), shape = as.factor(Year)), size =3) +
  geom_smooth(
    method = "lm",
    formula = y ~ x,
    se = FALSE,
    aes(color = as.factor(Year))
  ) +
  stat_poly_eq(
    aes(label = paste(
      # 自定义等式格式,强制截距和斜率保留1位小数
      sprintf("y == %.1f + %.1f*x", after_stat(coef)[[1]], after_stat(coef)[[2]]),
      # 保留原有的R²标签格式
      gsub('\\.', ".", after_stat(rr.label)),
      sep = "*plain(\", \")~~"
    )),
    label.x.npc = 0.85,
    label.y.npc = c(0.9, 0.85),
    formula = y ~ x,
    parse = TRUE,
    size = 4.5,
    color = c("black", "red")
  ) +
  geom_text_repel(aes(label = Variety, color = as.factor(Year)), size = 4.5) +
  scale_color_manual(values = c("black", "red", "black", "red")) +
  labs(y = expression(paste('SLA (cm' ^ 2, '·', 'g' ^ -1, ')')),
       x = "FTSWt") +
  theme_bw()

说明

  • sprintf("y == %.1f + %.1f*x", ...)中的%.1f强制所有系数保留1位小数,59.23会自动转换为59.2,其他已为一位小数的数值保持不变。
  • 移除了coef.digits参数,因为我们已经手动控制了小数位数格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:57:01