Let's say I were to execute a regression model in 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)
The way I would plot the coefficients of this model would be to use the following function, from 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(model)
However, this plot will not plot the coefficients in a sorted manner, eg greatest to least in descending order.
I have tried using order(coeffs)
in the above function, but this doesn't seem to work. How does one easily plot the coefficients in decreasing order?
you can order the coefficients and then plot the data:
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)
You can also adapt your function to sort the coefficients:
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.