[R可视化]绘制线性回归模型系数的正负和大小

setwd("C:\\Users\\yangzifeng_i\\Desktop\\data")
library(readr)
dta0<-read.csv("forestfires.csv")
dta1<-dta0[,-which(names(dta0)%in%c("month","day"))]

#线性模型建模
all<-dta1
##变量标准化
for (i in 1:length(all))
{
  all[,i]<-(all[,i]-mean(all[,i]))/sd(all[,i])
}
##构造逻辑回归模型
lm_res<-lm(area~.,data=all)

#系数大小和正负可视化
library(ggplot2)
coef<-as.data.frame(lm_res$coefficients)
coef$var<-row.names(coef)
colnames(coef)[1]<-"coef"
coef<-coef[-1,]
coef$pos = coef$coef>0
ggplot(coef,aes(x = reorder(var,-coef),y = coef,fill = pos))+
  geom_bar(stat = 'identity',position = 'identity')+
  scale_x_discrete(labels = c("X","Y","FFMC","DMC","DC","ISI","temp","RH","wind","rain"))+
  theme(axis.text.x = element_text(angle = 50,hjust = 1,vjust = 1))+
  labs(fill = "系数正负",x = "变量",y="系数")

猜你喜欢

转载自blog.csdn.net/TOMOCAT/article/details/82151795