[英]Plot coefficients with confidence intervals in R
I have a sample regression as below. 我有一个样本回归如下。
y it = λ i + δ t + α 1 TR + ∑ t ∈ {2,,,T} β t TR*δ t ý 它 =λ1 +δT +α1 TR +Σ 吨∈{2 ,,, T】β 吨 TR *δ 吨
That is, I have time-varying coefficients, β t . 也就是说,我有时变系数β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). 根据回归结果,我想用置信区间绘制系数(X轴是时间,Y轴是系数值)。
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? 如何用置信区间绘制tr*weekid
系数?
We may use ggcoef
from GGally
. 我们可以使用ggcoef
的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")
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
. 更新 :因为,至少在某种程度上,我们可以像ggplot2
输出一样处理这个图,我们可以用coord_flip
翻转轴。 That's not the best idea since the variable names are long, so just for demonstration I combined it with angle = 30
. 这不是最好的主意,因为变量名称很长,所以只是为了演示我将它与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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.