I want to plot the coefficients of a regression model in a bar plot that also contains the confidence intervals for each coefficient.
M=lm(mpg ~ . , data = mtcars)
confint(M, level = 0.9)
The basic trick for drawing confidence bars in R, if you don't want to use any packages (
gplot::barplot2), is to use
arrows(...,angle=90) (or use
segments() if you don't want "serifs" on your error bars)
M <- lm(mpg ~ . , data = mtcars) c0 <- coef(M) cc <- confint(M, level = 0.9)
Draw the plot:
b <- drop(barplot(c0,ylim=range(c(cc)))) ## b stores vector of x positions arrows(b,c0,b,cc[,1],angle=90,length=0.05) ## lower bars arrows(b,c0,b,cc[,2],angle=90,length=0.05) ## upper bars
I would actually argue that you should use
points() rather than
barplot for the basic plot, since barplots don't make as much sense for values that could be positive or negative. It may also make sense to rotate the plot 90 degrees, to make it easier to plot long parameter names.
By the time you've done all this, you've more or less recapitulated
arm::coefplot. (Another option is to look inside the code of
coefplot, to see what it's actually doing ...)