Reputation: 163
I would like to generate graphs for different datasets, with the same variables, but in which the years change. So far I can generate the graphs, without a legend, doing this:
levelsof year, local(lyear)
foreach l of local lyear {
local fig `fig' scatter mpg time if year==`l', connect(l) ||
}
graph twoway `fig'
I want to add a legend showing each year. For example, doing it without a loop, I would add the option:
graph twoway `fig', legend(lab(1 "2010") lab(2 "2011") lab(3 "2012"))
Is there a way to have the years appear in the legend as part of a loop? The years, and the number of years, change from dataset to dataset and this would be helpful.
Upvotes: 0
Views: 923
Reputation: 715
This is not a comment on the (presumably better) answer above, but for future reference you can do all sorts of marvellous things with local macros. Just build a loop that updates the year (or anything else), then put this in a macro and use the macro for the options.
Here's a snippet from an example that I used to generate rug plots in Stata.
foreach llevel of local llevels {
local pposition: list posof "`llevel'" in llevels
local rposition = `ssize'-`pposition'+1
local iintensity=1-(0.7*((`rposition')/`maxlevels'))
local rrug "`rrug' (scatter rugzero `rugvar'"
local rrug "`rrug' if `rugvar'_pickone &"
local rrug "`rrug' `rugvar'_cat==`llevel' & `my_touse',"
local rrug "`rrug' xaxis(`axis') msymbol(none) mlab(ruglabel)"
local rrug "`rrug' mlabcolor(*`iintensity')"
local rrug "`rrug' mlabposition(`clock') )"
}
Upvotes: 1
Reputation: 37208
My short answer is that I would not draw such a graph with a loop at all.
Here is one way to do it:
separate mpg, by(year) veryshortlabel
twoway connected `r(varlist)' time, sort
Here is another way to do it:
ssc inst sepscatter
sepscatter mpg time, sep(year) recast(connected) sort
You need only install sepscatter
once.
Detail: this
legend(lab(1 "2010") lab(2 "2011") lab(3 "2012"))
is easier as
legend(order(1 "2010" 2 "2011" 3 "2012"))
Upvotes: 2