R语言之线性,多项式拟合及可视化
2019-02-28 本文已影响0人
Oodelay
加载并显示示例数据
data(mtcars)
head(mtcars)#查看前5行,前10列
summary(mtcars)#按列统计
初步可视化
library(PerformanceAnalytics)#加载包
chart.Correlation(mtcars, histogram=TRUE, pch=19)
1、 线性拟合
lm1 <- lm(mpg~disp, data = mtcars)
su1 = summary(lm1)
初步可视化
library('ggpmisc')
f1 <- y ~ x #定义回归方程
library('ggplot2')
p1 <- ggplot(mtcars, aes(disp, mpg)) + theme_bw()+
geom_point(show.legend = FALSE,color = 'blue',size = 5) +
ggtitle('nonlinear fit')+
geom_smooth(method = c('loess'), se=FALSE, col = 'black', span=0.5) + ##不规则拟合
geom_smooth(method = "lm", formula = y ~ poly(x,2),color='blue',size = 2,se = T)+ ##二项式拟合
stat_poly_eq(formula = f1,
aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse = TRUE,label.x.npc = "right", label.y.npc = "top",size = 3) +#添加注释文字
theme(axis.title= element_text(color = 'black',size= 12,face = 'bold'),
axis.text = element_text(color = 'black',size = 10,face = 'bold'),
plot.title = element_text(hjust = 0.5,size = 20,color = 'blue'))
输出图片
ggsave(p1,filename = 'p1.jpg',width = 4,height = 4,dpi = 600)
2、多项式拟合
lm2 = lm(mpg~disp + I(disp^2),data = mtcars)
su2 = summary(lm2)
初步可视化
f2 <- y ~ x + I(x^2) #定义回归方程
p2 <- ggplot(mtcars, aes(disp, mpg)) + theme_bw()+
geom_point(show.legend = FALSE,color = 'blue',size = 5) +
ggtitle('nonlinear fit')+
geom_smooth(method = c('loess'), se=FALSE, col = 'black', span=0.5) + ##不规则拟合
geom_smooth(method = "lm", formula = y ~ poly(x,2),color='blue',size = 2,se = T)+ ##二次拟合
stat_poly_eq(formula = f2,
aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse = TRUE,label.x.npc = "right", label.y.npc = "top",size = 3) +#添加注释文字
theme(axis.title= element_text(color = 'black',size= 12,face = 'bold'),
axis.text = element_text(color = 'black',size = 10,face = 'bold'),
plot.title = element_text(hjust = 0.5,size = 20,color = 'blue'))
保存图片
ggsave(p2,filename = 'p2.jpg',width = 4,height = 4,dpi = 600)