stata-visual-library icon indicating copy to clipboard operation
stata-visual-library copied to clipboard

sorted stacked bar graph

Open luizaandrade opened this issue 4 years ago • 0 comments

Here's some mock code that I created to answer a question on how to create a sorted stacked bar graph at region level starting from a hosehold-level dataset

clear
set obs 20000
gen random = rnormal(0, 2)
gen gender = random >.6
gen order = _n
xtile district = order, nq(6)
drop random
bys district: gen id = district * 1000000 + _n

* Collapse to district level
collapse (count) id, by(district gender)

* One column per gender
reshape wide id, i(district) j(gender)


* Calculate percentages
egen total = rowtotal(id?), m

foreach var of varlist id? {
    replace `var' = (`var'/total) * 100
}

graph bar 	Male Female, ///
			over(district, ///
				sort(1) descending) ///
			stack 

luizaandrade avatar Feb 19 '21 18:02 luizaandrade