gpt4 book ai didi

r - 我们能否整齐地将回归方程与R2和p值对齐?

转载 作者:行者123 更新时间:2023-12-03 13:47:15 25 4
gpt4 key购买 nike

将回归方程式,R2和p值(用于方程式)整齐地添加到 ggplot 图中的最佳(最简单)方法是什么?理想情况下,它应该与组和构面兼容。

这第一个图具有回归方程,以及使用 ggpubr 按组分组的r2和p值,但它们未对齐?我想念什么吗?可以将它们作为一个字符串包含在内吗?

library(ggplot)
library(ggpubr)

ggplot(mtcars, aes(x = wt, y = mpg, group = cyl))+
geom_smooth(method="lm")+
geom_point()+
stat_regline_equation()+
stat_cor(aes(label = paste(..rr.label.., ..p.label.., sep = "*`,`~")),
label.x.npc = "centre")

plot1

这是 ggpmisc 的选项,它的位置有些奇怪。
编辑奇怪的放置是由 geom=text引起的,我已经注释掉它以提供更好的放置,并添加了`label.x =“right”来防止过度绘图。由于@ dc37标记的上标问题,根据 ggpubr ,我们仍然存在misalignemnt
#https://stackoverflow.com/a/37708832/4927395
library(ggpmisc)

ggplot(mtcars, aes(x = wt, y = mpg, group = cyl))+
geom_smooth(method="lm")+
geom_point()+
stat_poly_eq(formula = "y~x",
aes(label = paste(..eq.label.., ..rr.label.., sep = "*`,`~")),
parse = TRUE)+
stat_fit_glance(method = 'lm',
method.args = list(formula = "y~x"),
#geom = 'text',

aes(label = paste("P-value = ", signif(..p.value.., digits = 4), sep = "")))

plot2_edited

我确实找到了一个很好的解决方案,可以将相关的统计数据整合在一起,但是这需要在ggplot之外创建回归,并创建一堆字符串操作绒毛-这样简单吗?而且,它不(按当前编码)处理分组,也不处理构面。
#https://stackoverflow.com/a/51974753/4927395
#Solution as one string, equation, R2 and p-value
lm_eqn <- function(df, y, x){
formula = as.formula(sprintf('%s ~ %s', y, x))
m <- lm(formula, data=df);
# formating the values into a summary string to print out
# ~ give some space, but equal size and comma need to be quoted
eq <- substitute(italic(target) == a + b %.% italic(input)*","~~italic(r)^2~"="~r2*","~~p~"="~italic(pvalue),
list(target = y,
input = x,
a = format(as.vector(coef(m)[1]), digits = 2),
b = format(as.vector(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3),
# getting the pvalue is painful
pvalue = format(summary(m)$coefficients[2,'Pr(>|t|)'], digits=1)
)
)
as.character(as.expression(eq));
}

ggplot(mtcars, aes(x = wt, y = mpg, group=cyl))+
geom_point() +
geom_text(x=3,y=30,label=lm_eqn(mtcars, 'wt','mpg'),color='red',parse=T) +
geom_smooth(method='lm')

enter image description here

最佳答案

我已经更新了“ggpmisc”以简化此过程。版本0.3.4现在正在向CRAN过渡,源代码包已在线,二进制文件应在几天内构建。

library(ggpmisc) # version >= 0.3.4 !!

ggplot(mtcars, aes(x = wt, y = mpg, group = cyl)) +
geom_smooth(method="lm")+
geom_point()+
stat_poly_eq(formula = y ~ x,
aes(label = paste(..eq.label.., ..rr.label.., ..p.value.label.., sep = "*`,`~")),
parse = TRUE,
label.x.npc = "right",
vstep = 0.05) # sets vertical spacing

enter image description here

关于r - 我们能否整齐地将回归方程与R2和p值对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61266084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com