如何更改 stat_regline_equation() 中 R 平方的有效数字?

问题描述 投票:0回答:2

这是我的数据示例:

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) +
  stat_regline_equation(aes(label = ..rr.label..),
                        label.x = 4, 
                        label.y = 5.8, 
                        size = 6) +
  stat_regline_equation(label.x = 4, 
                        label.y = 6.5, 
                        size = 6)

enter image description here

这条线与数据不太完美,但我仍然得到 1 的 R 平方。如何增加 R 平方的有效数字或小数位数以获得更准确的 R 平方?

非常感谢!

r ggplot2 ggpubr
2个回答
1
投票

另一种选择可能是首先使用

lm
summary
计算系数,然后使用
gsub
更改用
ggplot_build
绘制的系数,以更改绘制系数的图层的标签。这是一些可重现的代码:

library(ggplot2)
library(ggpubr)
model = lm(weight~surface_area, data = df)
r_squared = summary(model)$r.squared
r_squared
#> [1] 0.9995947
p = ggplot(data = df, aes(x = surface_area, y = weight)) + geom_point() +
  geom_smooth(method = 'lm',
              se = FALSE) +
  stat_regline_equation(aes(label = ..rr.label..),
                        label.x = 4, 
                        label.y = 5.8, 
                        size = 6) +
  stat_regline_equation(label.x = 4, 
                        label.y = 6.5, 
                        size = 6)

q <- ggplot_build(p)
q$data[[3]]$label = gsub("1", as.character(r_squared), q$data[[3]]$label)
q <- ggplot_gtable(q)
plot(q)

创建于 2023-03-24,使用 reprex v2.0.2


如果您想

round
您的系数,您可以使用
round
函数来计算系数,如下所示:

library(ggplot2)
library(ggpubr)
model = lm(weight~surface_area, data = df)
r_squared = summary(model)$r.squared
p = ggplot(data = df, aes(x = surface_area, y = weight)) + geom_point() +
  geom_smooth(method = 'lm',
              se = FALSE) +
  stat_regline_equation(aes(label = ..rr.label..),
                        label.x = 4, 
                        label.y = 5.8, 
                        size = 6) +
  stat_regline_equation(label.x = 4, 
                        label.y = 6.5, 
                        size = 6)

q <- ggplot_build(p)
q$data[[3]]$label = gsub("1", as.character(round(r_squared, 4)), q$data[[3]]$label)
q <- ggplot_gtable(q)
plot(q)

创建于 2023-03-24,使用 reprex v2.0.2


0
投票

要更改 r 平方位数,最好使用激发该函数的包(即

ggpmisc::stat_ploy_eq()
) - 请参阅 https://github.com/kassambara/ggpubr/issues/312

library(tidyverse)
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))

df %>% 
  ggplot(aes(x = surface_area, y = weight)) +
  geom_smooth(method = 'lm',
              se = FALSE) +
  geom_point() +
  stat_poly_eq(aes(label = after_stat(rr.label)),
               rr.digits = 5) +
  theme_bw()

创建于 2024 年 12 月 27 日,使用 reprex v2.1.1

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.