按目标变量排序图形条,然后排序变量

时间:2017-10-16 11:14:10

标签: stata

我制作了大量的图表,比较了两组(例如男/女)的多个变量。标准图形条形图输出将所有男性酒吧组合在一起,并将所有女性酒吧组合在一起。我希望找到一种简单的方法来制作条形图,它首先按目标变量(即绘制的变量)对条形图进行组合,然后按-over-变量进行组合,例如性别。

我有一个方法可以做到这一点,但它非常麻烦。见下图。

*Set seed + obs
clear
set seed 442
set obs 100

*Generate two outcomes
gen x1 = uniform()
gen x2 = uniform()

*Generate crossing variable
gen gender = 0 in 1/50
replace gender = 1 in 51/100
label define gender_lab 0 "Male" 1 "Female"
label values gender gender_lab

*Extract means by gender
gen b_male = .
gen b_female = .
sum x1 if gender == 0 
replace b_male = r(mean) in 1
sum x1 if gender == 1
replace b_female = r(mean) in 1
sum x2 if gender == 0
replace b_male = r(mean) in 2
sum x2 if gender == 1
replace b_female = r(mean) in 2

*Establish order of graph
gen index_male = _n*3 in 1/2
gen index_female = (_n*3) + 1 in 1/2


*This is what -graph bar- produces naturally
graph bar x1 x2, over(gender)

*This is closer to what I want
twoway bar b_male index_male || bar b_female index_female, xlabel(3.5 "x1" 6.5 "x2", notick labgap(4)) xmlabel(3 "Male" 4 "Female" 6 "Male" 7 "Female") legend(off)

是否有一种简单的方法可以使用graph bar但仍然可以建立我想要的排序顺序?我有时会每天制作几十张这样的图表,所以我希望尽可能避免不必要的步骤。

1 个答案:

答案 0 :(得分:3)

这是一个模型问题:非常感谢!

我将首先复制您的代码,并进行一些可能感兴趣的小简化。

*Set seed + obs
clear
set seed 442
set obs 100

*Generate two outcomes
gen x1 = runiform()
gen x2 = runiform()

*Generate crossing variable
gen gender = _n > 50 
label define gender_lab 0 "Male" 1 "Female"
label values gender gender_lab

*Extract means by gender
sum x1 if gender == 0 
gen b_male = r(mean) in 1
sum x1 if gender == 1
gen b_female = r(mean) in 1
sum x2 if gender == 0
replace b_male = r(mean) in 2
sum x2 if gender == 1
replace b_female = r(mean) in 2

*Establish order of graph
gen index_male = _n*3 in 1/2
gen index_female = (_n*3) + 1 in 1/2

*This is what -graph bar- produces naturally
graph bar x1 x2, over(gender) name(G1) 

*This is closer to what I want
twoway bar b_male index_male || bar b_female index_female, ///
xlabel(3.5 "x1" 6.5 "x2", notick labgap(4))                ///
xmlabel(3 "Male" 4 "Female" 6 "Male" 7 "Female") legend(off) name(G2)  

好消息是,一旦您安装了来自SSC的Eric A. Booth和我自己statplot,就会有一个单线解决方案。 (Eric的电子邮件地址是帮助文件不再是最新的。)

ssc inst statplot 
statplot x1 x2, over(gender)
statplot x1 x2, over(gender) recast(bar)
statplot x1 x2, over(gender) recast(bar) asyvars yla(, ang(h)) ///
bar(2, bcolor(orange*0.8)) bar(1, bcolor(blue*0.8))

这是显示完成内容的最后一张图。

statplot默认为表示您展示的内容,因此您不必计算均值。其他统计数据可用。

enter image description here