Stefan Stefan - 1 month ago 6
R Question

Plotting coefficients and corresponding confidence intervals

I want to plot the coefficients of a regression model in a bar plot that also contains the confidence intervals for each coefficient.

e. g.

M=lm(mpg ~ . , data = mtcars)

confint(M, level = 0.9)

--> How to plot these two information in one bar plot?

Maybe its possible to sort the coefficients depending on their value, too?

I looked around and found
, but actually I want to do it without a library because it should be easy to use for beginners and should explain how plots can be used. If somebody knows a good package, its fine too. But I want to build it "myself", so how can I find out what is happening behind? Is it possible to get/examine the code of one specific method in a package?

Additionally, I try to visualize the significane of each variable/combination (if its a DiD model).
Therefore I want to create a barplot to list the (most) significant coefficients in a sorted order. The
command lists the Coefficients and the corresponding significance codes. Each coefficient with a high significance code (***) should be listend first, then the ** and then the *. The dot and '' should not be included.

Any ideas?



The basic trick for drawing confidence bars in R, if you don't want to use any packages (plotrix::plotCI, or 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 ...)