Using xtset to produce a panel data graph

Below is a worked example of using xtset to produce a panel data graph:

The commands I used in a do-file are as below:

clear
set more off
set obs 3
gen id=_n
expand 10
bysort id: gen year=2000+_n-1
gen data=runiform()*100
list, sepby(id)

// producing the graph
xtset id year
bysort year :egen ave=mean(data)
replace ave=. if id!=1
gen mean_lab="mean" if id==1 & year==2009
sort id year
xtline data, overlay addplot(                    ///
(line ave year,lwidth(thick))                    ///
(scatter data year if year==2009,mlab(id))       ///
(scatter ave year if year==2009,mlab(mean_lab)), ///
legend(off))

Alternatively, you can use:

twoway (line data year,c(L))                     ///
(line ave year,lwidth(thick))                    ///
(scatter data year if year==2009,mlab(id))       ///
(scatter ave year if year==2009,mlab(mean_lab)), ///
legend(off) ytitle("data")

You may find more useful information in the book A Visual Guide to Stata Graphics

47 views

© 2020 by Survey Design and Analysis Services. 

  • LinkedIn
  • Facebook
  • Twitter
  • YouTube