Rem*_*i.b 101 regression r linear-regression ggplot2
我正努力在ggplot上添加回归线.我首先尝试使用abline,但我没有设法让它工作.然后我尝试了这个......
data = data.frame(x.plot=rep(seq(1,5),10),y.plot=rnorm(50))
ggplot(data,aes(x.plot,y.plot))+stat_summary(fun.data=mean_cl_normal) +
geom_smooth(method='lm',formula=data$y.plot~data$x.plot)
Run Code Online (Sandbox Code Playgroud)
但它也没有用.
Did*_*rts 145
在一般情况下,提供自己的公式,你应该使用的参数x和y将对应于你提供的值ggplot()-在这种情况下x将被解释为x.plot与y作为y.plot.有关平滑方法和公式的更多信息,您可以在函数的帮助页面中找到stat_smooth()它,因为它是默认属性使用的geom_smooth().
ggplot(data,aes(x.plot, y.plot)) +
stat_summary(fun.data=mean_cl_normal) +
geom_smooth(method='lm', formula= y~x)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是ggplot()调用中提供的相同x和y值,并且需要绘制线性回归线,那么您不需要在里面使用公式geom_smooth(),只需提供method="lm".
ggplot(data,aes(x.plot, y.plot)) +
stat_summary(fun.data= mean_cl_normal) +
geom_smooth(method='lm')
Run Code Online (Sandbox Code Playgroud)
Ste*_*anK 38
正如我刚才想到的,如果你有一个模型适合多元线性回归,上面提到的解决方案将无法工作.
您必须手动创建线条作为包含原始数据框的预测值的数据框(在您的情况下data).
它看起来像这样:
# read dataset
df = mtcars
# create multiple linear model
lm_fit <- lm(mpg ~ cyl + hp, data=df)
summary(lm_fit)
# save predictions of the model in the new data frame
# together with variable you want to plot against
predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)
# this is the predicted line of multiple linear regression
ggplot(data = df, aes(x = mpg, y = hp)) +
geom_point(color='blue') +
geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))
Run Code Online (Sandbox Code Playgroud)
# this is predicted line comparing only chosen variables
ggplot(data = df, aes(x = mpg, y = hp)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE)
Run Code Online (Sandbox Code Playgroud)
显而易见的解决方案是geom_abline:
geom_abline(slope = data.lm$coefficients[2], intercept = data.lm$coefficients[1])
Run Code Online (Sandbox Code Playgroud)
哪里data.lm是一个lm对象,data.lm$coefficients看起来是这样的:
data.lm$coefficients
(Intercept) DepDelay
-2.006045 1.025109
Run Code Online (Sandbox Code Playgroud)
在实践中,相同地使用stat_function来绘制回归线作为x的函数,方法是predict:
stat_function(fun = function(x) predict(data.lm, newdata = data.frame(DepDelay=x)))
Run Code Online (Sandbox Code Playgroud)
由于默认情况下n=101会计算点,因此效率略低,但灵活性更高,因为它将为支持的任何模型绘制预测曲线predict,例如npreg来自软件包np 的非线性。
注意:如果使用scale_x_continuous或scale_y_continuous某些值可能会被截断,因此geom_smooth可能无法正常工作。使用coord_cartesian缩放代替。
小智 5
我在博客上找到了这个功能
ggplotRegression <- function (fit) {
`require(ggplot2)
ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) +
geom_point() +
stat_smooth(method = "lm", col = "red") +
labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
"Intercept =",signif(fit$coef[[1]],5 ),
" Slope =",signif(fit$coef[[2]], 5),
" P =",signif(summary(fit)$coef[2,4], 5)))
}`
Run Code Online (Sandbox Code Playgroud)
一旦你加载了函数,你就可以简单地
ggplotRegression(fit)
Run Code Online (Sandbox Code Playgroud)
你也可以去 ggplotregression( y ~ x + z + Q, data)
希望这可以帮助。