如何在Stata中向线图添加因子/组变量

问题描述

我想使用xtline绘制随时间变化的连续变量的线图,并在每个数据点上覆盖散点图或标签,以指示此时的组成员身份。

* Example generated by -dataex-. To install: ssc install dataex
clear
input double(id year group variable)
 101 2003 3 12
 102 2003 2 10
 102 2005 1 10
 102 2007 2 10
 102 2009 1 10
 102 2011 2 10
 103 2003 4  3
 103 2005 2  1
 104 2003 4 50
 105 2003 4  8
 105 2005 4 12
 105 2007 4 12
 105 2009 4 12
 106 2003 1  6
 106 2005 1 28
 106 2007 2 15
 106 2009 2  4
 106 2011 3  4
 106 2015 1  2
 106 2017 1  2
end

xtset id year

xtline variable,overlay

enter image description here

我在此处添加/标记/标记了ID为103的组。

enter image description here

我有四个小组,希望也可以在图例中显示。

解决方案

preserve
separate variable,by(id) veryshortlabel
line variable101-variable106 year  ///
|| scatter variable year,///
mla(group) ms(none) mlabc(black) ytitle(variable)
restore

或者

xtline variable,overlay addplot(scatter variable year,mlabel(group))

enter image description here

解决方法

我建议在这里直接贴标签。它可能会产生稍微混乱的图形,但是您自己的示例已经很杂乱,只有添加更多详细信息,情况才会变得更糟。

这是一个可复制的示例。

webuse grunfeld,clear
set scheme s1color 
separate invest,by(company) veryshortlabel

line invest1-invest10 year,ysc(log)    ///
|| scatter invest year if year == 1954,///
mla(company) ms(none) mlabc(black) legend(off) yla(1 10 100 1000,ang(h)) ytitle(investment)

编辑:

在您的示例中,仅在一年中存在两个标识符。为了展示使用面板数据绘制线图的一些技巧,我将重点介绍其他技巧。

* Example generated by -dataex-. To install: ssc install dataex
clear
input double(id year group variable)
 101 2003 3 12
 102 2003 2 10
 102 2005 1 10
 102 2007 2 10
 102 2009 1 10
 102 2011 2 10
 103 2003 4  3
 103 2005 2  1
 104 2003 4 50
 105 2003 4  8
 105 2005 4 12
 105 2007 4 12
 105 2009 4 12
 106 2003 1  6
 106 2005 1 28
 106 2007 2 15
 106 2009 2  4
 106 2011 3  4
 106 2015 1  2
 106 2017 1  2
end

bysort id : gen include = _N > 1 
ssc install fabplot 
set scheme s1color 
fabplot line variable year if include,xla(2003 " 2003" 2010 2017 "2017 ") by(id) frontopts(lw(thick)) xtitle("") 

enter image description here

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...