我的数据中有两个变量的许多观察结果,例如
rep78
和 headroom
。
我想取第三个变量的平均值,例如每个
weight
+rep78
单元格内的 headroom
。对于每个 headroom
类别,我想分别在 x 轴上用 rep78
绘制这些平均值(连接点图)。我想更直观的思考方式是将 rep78
替换为 year
,将 headroom
替换为 state
。
我已经能够通过下面的代码得到我想要的东西:
sysuse auto2, clear
bys rep78 headroom: egen mean_w=mean(weight)
twoway (scatter mean_w rep78 if headroom==1.5, connect(l)) ///
(scatter mean_w rep78 if headroom==2.0, connect(l)) ///
(scatter mean_w rep78 if headroom==2.5, connect(l)) ///
(scatter mean_w rep78 if headroom==3.0, connect(l)) ///
(scatter mean_w rep78 if headroom==3.5, connect(l)) ///
(scatter mean_w rep78 if headroom==4.0, connect(l)) ///
(scatter mean_w rep78 if headroom==4.5, connect(l)) ///
(scatter mean_w rep78 if headroom==5.0, connect(l)), ///
legend(label(1 "1.5") label(2 "2.0") label(3 "2.5") ///
label(4 "3.0") label(5 "3.5") label(6 "4.0") ///
label(7 "4.5") label(8 "5.0"))
但是,有没有更简单(即更短)的方法来做到这一点?
我很乐意简化这段代码的所有部分。
感谢 MCVE!
你是对的。这是一种获得相同图表的较短解决方案,您也可以调整模数小细节:
sepscatter mean_w rep78, sep(headroom) recast(connected) name(G2, replace)
使用 SSC 的
sepscatter
,如 在 Statalist 上宣布的那样。使用 sepscatter
作为 Statalist 上的搜索词可以找到更多示例。
我在这里没有看到任何复杂的事情。
community-contributed命令
sepscatter
是一个很好的包装器,但如果代码简洁是一个问题,你也可以在不安装任何东西的情况下执行以下操作:
sysuse auto2, clear
bysort rep78 headroom: egen mean_w=mean(weight)
levelsof headroom, local(head)
foreach x of local head {
local scatterlist `scatterlist' (scatter mean_w rep78 if headroom == `x', connect(l))
}
twoway `scatterlist'
为了减轻任何精度问题,如果变量不是生成为 double 的,可以使用
float()
:
(scatter mean_w rep78 if headroom == float(`x'), connect(l))