【R画图学习21.4】ggplot2回归函数stat_function

我们在21.3主要讲了利用stat_smooth()、geom_smooth()来进行回归分析和曲线拟合。但是很多回归方法,特别对于大多数非线性回归而言,ggplot2及其拓展包中缺少作图方案,难以通过stat_smooth()、geom_smooth()直接作图。这时候,可以考虑使用stat_function()根据指定函数绘制拟合线。

如果已经提前计算出了回归式的各参数,则可以直接将已知的回归式指定给ggplot2函数stat_function()。stat_function()能够在作图时将自变量代入至已知的回归式中拟合响应变量的预测值,并使用平滑线连接响应变量的预测值获得回归线。在理论上,stat_function()可以实现对任意给定回归式的拟合线绘制。

所以和geom_smooth相比,前面属于利用内置的模型来拟合,stat_function则可以使用用户自定义的任何模型。


library(ggplot2)

library(patchwork)

======多次项的线性回归=======

#还是用MASS 包的示例数据集,波士顿郊区的房屋价值

library(MASS)

data(Boston)

#ggplot2 绘制低收入人口比例和居住地房屋价格的关系

p <- ggplot(data = Boston, aes(x = medv, y = lstat)) +

geom_point() +

theme_bw()

p

##手动通过 lm() 计算低收入人口比例和居住地房屋价格的二次线性关系

fit <- lm(lstat~medv+I(medv^2), data = Boston)

summary(fit)

p + stat_function(fun = function(x) -1.715*x+0.021*x^2+39.048, color = 'red', size = 1.2)

可以看出,会比前面默认的回归函数更适合数据的分布。

#我们也可以直接在 lm() 结果中提取回归系数(斜率)和截距,然后将提取出的值代入至 stat_function() 中。

b0 <- coefficients(fit)[1] #截距

b1 <- coefficients(fit)[2]  #线性的回归系数

b2 <- coefficients(fit)[3]  #二次方的回归系数

效果和上面是一样的。

p + stat_function(fun = function(x) b1*x+b2*x^2+b0, color = 'red', size = 1.2)


====指数回归的非线性参数回归=====

这次也是用21.3中crim和medv的数据。

p <- ggplot(data = Boston, aes(x = crim, y = medv)) +

geom_point() +

theme_bw()

p

从数据分布来看,明显不是线性分布,属于指数分布。

##参数非线性回归(nls)的拟合,以指数回归为例,参数中 a 和 b 的初始值手动指定。

mod <- nls(medv ~ a*crim^b, data = Boston, start = list(a = 2, b = 1.5))

summary(mod)

#根据 nls() 获得的参数估计,可知回归方程为 Y = 20.743X^-0.086,然后将这个回归式书写到 stat_function() 中。

p + stat_function(fun = function(x) 20.743*x^-0.086, color = 'red', size = 1.2)

#同样滴,我们也可以直接在 nls() 结果中提取 a 和 b 的值,然后将提取出的值代入至 stat_function() 中。

a <- coefficients(mod)[1]  #a 的值

b <- coefficients(mod)[2]  #b 的值

效果还上面是一样的。

p + stat_function(fun = function(x) a*x^b, color = 'red', size = 1.2)

你可能感兴趣的:(【R画图学习21.4】ggplot2回归函数stat_function)