将整齐地添加到ggplot图中的回归方程式,R2和p值(对于方程式而言)的最佳(最简单的方法是什么?)?理想情况下,它应该与刻面兼容。
此第一个图具有使用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")
这里是ggpmisc的一个选项,它的位置有些奇怪。
#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 = "")))
我确实找到了一个很好的解决方案,可以将相关的统计数据汇总在一起,但是这需要在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')
ggpubr
的可能解决方案是通过将Inf
传递到label.y
和Inf
或-Inf
传递到label.x
,将方程式和R2值放在图的顶部(取决于您是否愿意)在图的右侧或左侧)
由于R上的上标2,两个文本都不会对齐。因此,您必须使用vjust
和hjust
对其稍作调整,以对齐两个文本。
然后,它甚至适用于具有不同比例的多面图。
library(ggplot)
library(ggpubr)
ggplot(mtcars, aes(x = wt, y = mpg, group = cyl))+
geom_smooth(method="lm")+
geom_point()+
stat_regline_equation(label.x = -Inf, label.y = Inf, vjust = 1.5, hjust = -0.1, size = 3)+
stat_cor(aes(label = paste(..rr.label.., ..p.label.., sep = "*`,`~")),
label.y= Inf, label.x = Inf, vjust = 1, hjust = 1.1, size = 3)+
facet_wrap(~cyl, scales = "free")
它回答了您的问题吗?