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

如何调整stat_regline_equation()中R平方的有效数字?

解决R平方显示位数不足的问题

要让stat_regline_equation显示更多小数位数的R平方值,有两种简单可行的方法:

方法一:使用digits参数指定保留位数

stat_regline_equation(来自ggpmisc包)自带digits参数,可直接控制输出数值的小数位数。修改代码如下:

library(ggplot2)
library(ggpmisc)

df <- data.frame(surface_area = c(0.25, 1, 2.25, 4, 6.25),
                 weight = c(0.8, 3.267, 7.733, 13.533, 21.8333))

plot <- ggplot(data = df, aes(x = surface_area, y = weight)) + 
  geom_point() +
  geom_smooth(method = 'lm', se = FALSE) +
  # 设定R²显示5位小数
  stat_regline_equation(aes(label = ..rr.label..),
                        label.x = 4, 
                        label.y = 5.8, 
                        size = 6,
                        digits = 5) +
  # 同步调整回归方程的数值显示位数
  stat_regline_equation(label.x = 4, 
                        label.y = 6.5, 
                        size = 6,
                        digits = 5)
plot

方法二:自定义格式化字符串

如果需要更灵活的格式控制,可使用sprintf函数自定义输出内容,精准指定小数位数:

library(ggplot2)
library(ggpmisc)

df <- data.frame(surface_area = c(0.25, 1, 2.25, 4, 6.25),
                 weight = c(0.8, 3.267, 7.733, 13.533, 21.8333))

plot <- ggplot(data = df, aes(x = surface_area, y = weight)) + 
  geom_point() +
  geom_smooth(method = 'lm', se = FALSE) +
  # 自定义R²显示为5位小数
  stat_regline_equation(aes(label = sprintf("R² = %.5f", ..r.squared..)),
                        label.x = 4, 
                        label.y = 5.8, 
                        size = 6) +
  # 自定义回归方程系数显示为3位小数
  stat_regline_equation(aes(label = sprintf("y = %.3fx + %.3f", ..coef.ls..[2], ..coef.ls..[1])),
                        label.x = 4, 
                        label.y = 6.5, 
                        size = 6)
plot

两种方法都能突破默认的位数限制,展示真实的R平方数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:37:28