Stefan - 5 months ago 23

R Question

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.

`attach(mtcars)`

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

barplot(coefficients(M))

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

`coefplot`

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

`summary(M)`

Any ideas?

Thanks!

Answer

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 ...)