2
votes

I have a sample regression as below.
yit = λi + δt + α1TR + ∑ t ∈ {2,,,T} βtTR*δt

That is, I have time-varying coefficients, βt. With the regression result, I would like to plot coefficients with confidence intervals (X-axis is time and Y-axis is the coefficient values).

Here is the sample data

y = rnorm(1000,1)
weekid = as.factor(sample.int(52,size = 1000,replace = T))
id = as.factor(sample.int(100,size = 1000,replace = T))
tr = as.factor(sample(c(0,1),size = 1000, prob = c(1,2),replace = T))
sample_lm = lm(y ~ weekid + id + tr*weekid)
summary(sample_lm)

How can I plot coefficients for tr*weekid with the confidence intervals?

1
So what exactly do you want this plot to look like? If you use random numbers in your example, it's best to also include a set.seed() so we can get the same values as you to replicate the data. - MrFlick

1 Answers

3
votes

We may use ggcoef from GGally. One issue is that you want to visualize only a subset of coefficients. In that case we can do

ggcoef(tail(broom::tidy(sample_lm, conf.int = TRUE), 51), sort = "ascending")

enter image description here

Update: since, at least to some extent, we can deal with this graph as with a ggplot2 output, we may flip the axes with coord_flip. That's not the best idea since the variable names are long, so just for demonstration I combined it with angle = 30. By default the coefficients are sorted by name, which again isn't what one may be after. As to fix that, we first need to define the coefficient names as a factor variable and specify their levels. That is, we have

tbl <- tail(broom::tidy(sample_lm, conf.int = TRUE), 51)
tbl$term <- factor(tbl$term, levels = tbl$term)
ggcoef(tbl) + coord_flip() + theme(axis.text.x = element_text(angle = 30))

enter image description here