边缘图的最佳拟合线

时间:2018-03-01 23:21:43

标签: graph regression stata margins

我正在尝试创建边距图并添加一条最适合绘制边际值的线以显示趋势,因为边距是针对年度虚拟对象而绘制的。边缘图可以在这里看到,其中红线显示我想要获得的结果(但只是我已经绘制的估计线):https://imgur.com/a/Uh2Q5

我的数据快照(仅限于与此帖相关的变量)可在此处查看:https://imgur.com/a/FqsWm

关于如何在边缘图上实现这条拟合线的任何建议都将非常感谢!

由于

1 个答案:

答案 0 :(得分:0)

目前尚不清楚您想要绘制什么样的边距以及底层模型是什么,但这里有一些代码可以帮助您入门:

sysuse auto, clear
reg price i.rep78 c.weight
eststo margins: margins rep78, post
// eststo margins: margins, dydx(rep78) post

/* store margins output as a variable */
local levels: colnames e(b)
gen margins = .
foreach j of local levels  {
    replace margins = _b[`j'] if `j'==1
}

/* run a regression on the output of margins */
reg margins c.rep78
eststo lfit: margins, over(rep78) post

/* plot both margins and linear approximation */
coefplot (margins) (lfit, recast(line) offset(0)), vertical xlabel(, alternate)

drop margins

这会产生:

enter image description here

coefplot来自SSC。

以下是评论中问题的解决方案:

sysuse auto, clear
reg price c.mpg##i.rep78 c.weight
margins r.rep78, dydx(mpg) post
/* store interaction coefficients as a variable */
local levels: colnames e(b)
gen margins = .
foreach j of local levels  {
    replace margins = _b[`j'] if `j'==1
}
/* plot margins with added line */
marginsplot, addplot(lfit margins rep78) recast(scatter) legend(off)