Home > Blockchain >  Separate coefficients from lm() and plot next to each other
Separate coefficients from lm() and plot next to each other

Time:12-31

I'm running a simple lm() regression that returns 4 coefficients. I would like to plot them two by two (next to each other, with different colours), as if I would have run two models giving two coefficients each.

Minimal example:

Y <- runif(100, 0, 1)
G <- round(runif(100, 0, 1))
C <- round(runif(100, 0, 1))
df <- data.frame(Y, G, T)

out <- lm(Y ~ G   factor(C)   G*factor(C), data=df)
summary(out)
coefplot(out) # from library(fixest)

enter image description here

However, I would like to have (Intercept) and G at the same place on the X axis next to each other, and factor(C)1 and G:factor(C)1. A possible solution could be to separate the output from lm() and plot it as: coefplot(list(out1, out1)). How would this work? What other way could work?

CodePudding user response:

You could roll your out of coef and confint.

pdat <- cbind(coef(out), confint(out))

xs <- c(0.6, 1.1, 2.9, 3.4)
plot(xs, pdat[, 1], pch=20, xlim=c(0, 4), ylim=range(pdat), col=2:3, xaxt='n',
     main='My Model', xlab='Coefficients', ylab='Beta')
axis(1, xs, F)
mtext(rownames(pdat), 1, .5, at=xs, cex=.7)
arrows(xs, pdat[, 2], xs, pdat[, 3], code=3, angle=90, length=.05, col=2:3)
abline(h=0)
grid()

enter image description here


Data:

set.seed(264211)
df <- data.frame(Y=runif(100, 0, 1), G=round(runif(100, 0, 1)), C=round(runif(100, 0, 1)))
out <- lm(Y ~ G   factor(C)   G*factor(C), data=df)

CodePudding user response:

1) Using nlme perform a regression separately for each level of C and then issue two coefplot calls.

library(nlme)
library(fixest)

L <- lmList(Y ~ G | C, df)

opar <- par(mfrow = 1:2)
ylim <- extendrange(unlist(confint(L)))
coefplot(L[[1]], col = "red", lwd = 2, ylim = ylim)
title(names(L)[1])
coefplot(L[[2]], col = "green", lwd = 2, ylim = ylim)
title(names(L)[2])
par(opar)

(continued after chart)

screenshot

2) or maybe this is what you want. L is from above

coefplot(L[[1]], lwd = 5, col = "grey")
coefplot(L[[2]], add = TRUE, col = "red")
legend("topright", legend = names(L), col = c("grey", "red"), lty = 1)

(continued after chart)

screenshot

3) Another approach is to use the model shown here.

fm <-  lm(Y ~ C / G   0, transform(df, C = factor(C)))
nms <- variable.names(fm)
ix <- grep("G", nms)
g <- list(intercept = nms[-ix], slope = nms[ix])
coefplot(fm, group = g)

screenshot

  • Related