如何在R中绘制lm()/ glm()回归模型的排序系数?

时间:2017-07-06 12:56:37

标签: r plot ggplot2

假设我要在R中执行回归模型:

library(data.table)
mtcars = as.data.table(mtcars)
dt = colSums(mtcars)

> dt
     mpg      cyl     disp       hp     drat       wt     qsec       vs 
 642.900  198.000 7383.100 4694.000  115.090  102.952  571.160   14.000 
      am     gear     carb 
  13.000  118.000   90.000 

model = lm(formula=mpg~cyl, data=dt)

我绘制此模型系数的方法是使用以下函数,来自Extract regression coefficient values

plot_coeffs <- function(mlr_model) {
  coeffs <- coefficients(mlr_model)
  mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
  lablist <- names(coeffs)
  text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}

plot_coeffs(模型)

然而,该图不会以分类的方式绘制系数,例如,最大到最小的降序。

我尝试在上面的函数中使用order(coeffs),但这似乎不起作用。如何按递减顺序轻松绘制系数?

2 个答案:

答案 0 :(得分:1)

您可以订购系数,然后绘制数据:

model = lm(formula=mpg~cyl, data=mtcars)

coeffs <- coefficients(model)
coeffsord <- coeffs[order(coeffs)]

barplot(coeffsord, col="#3F97D0", xaxt='n', main="Regression Coefficients")
text(1:2, labels = names(coeffsord), srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)

答案 1 :(得分:1)

您还可以调整函数以对系数进行排序:

plot_coeffs_S <- function(mlr_model) {
  coeffs <- sort(coefficients(mlr_model), decreasing = TRUE)  ### changed
  mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
  lablist <- names(coeffs)
  text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}