'Can the grc1leg command combine the legend for multiple kdensity plots in Stata?
I am creating kdensity curves for income (kerr_income) distributions in a year (taxyear) by gender (male). However, when I create the kdensity plot, I cannot combine the legend to differentiate by gender and not each curve. I want one legend to show a male and female distribution only.
kdensity kerr_income if male==0 & taxyear == 2008, addplot(kdensity kerr_income if male==1 & ///
taxyear == 2008) name(g1, replace) ///
legend(label(1 "Female") label(2 "Male"))
kdensity kerr_income if male==0 & taxyear == 2009, legend(off) name(g2, replace) ///
addplot(kdensity kerr_income if male==1 & taxyear == 2009, legend(off) name(g3, replace) || ///
kdensity kerr_income if male==0 & taxyear == 2010, legend(off) name(g4, replace) || ///
kdensity kerr_income if male==1 & taxyear == 2010, legend(off) name(g5, replace))
grc1leg g1 g2 g3 g4 g5, legendfrom(g1)
I am using Stata 14. Any help would be appreciated!
Solution 1:[1]
I haven't tried grc1leg on this kind of problem, or indeed much at all, but the problem you're facing can be avoided altogether. You need code so that you can exploit the by() option's scope for arranging all the scaffolding and cutting down the duplicate legends.
Here is a demonstration. Note that you need multidensity from SSC.
* want a 2 x 4 grouping
sysuse auto, clear
xtile qprice=price, nq(4)
preserve
egen group = group(qprice foreign), label
tab group
* ssc install multidensity
multidensity generate mpg, by(group) min(5) max(45)
keep _x* _density*
gen id = _n
reshape long _density _x, i(id) j(g)
gen foreign = !mod(g, 2)
separate _density, by(foreign)
label var _density0 "Domestic"
label var _density1 "Foreign"
gen G = ceil(g/2)
line _density? _x, by(G, note("Quartile bins of price")) sort xla(5(10)45) xtitle(Miles per gallon) ytitle(Density) name(demo, replace)
restore
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

