// 清除之前的数据和变量 clear all // 输入数据 input str10 race str15 age_group owns_cat does_not_own_cat "White" "youth" 65 84 "White" "middle-aged" 92 107 "White" "elderly" 87 120 "Black" "youth" 4 14 "Black" "middle-aged" 3 17 "Black" "elderly" 4 15 "Other" "youth" 7 13 "Other" "middle-aged" 4 19 "Other" "elderly" 4 12 // 计算每个组别的拥有猫和不拥有猫的百分比 gen total = owns_cat + does_not_own_cat gen owns_cat_percentage = (owns_cat / total) * 100 gen does_not_own_cat_percentage = (does_not_own_cat / total) * 100 // 重构数据为长格式 gen cat_status = "owns_cat" gen percentage = owns_cat_percentage tempfile temp save `temp', replace gen cat_status = "does_not_own_cat" gen percentage = does_not_own_cat_percentage append using `temp' // 将 cat_status 转换为标签变量 replace cat_status = "Owns Cats" if cat_status == "owns_cat" replace cat_status = "Does Not Own Cats" if cat_status == "does_not_own_cat" encode cat_status, gen(cat_status_encoded) label values cat_status_encoded cat_status_lbl // 添加对应的数量 gen population = . replace population = owns_cat if cat_status == "Owns Cats" replace population = does_not_own_cat if cat_status == "Does Not Own Cats" // 绘制百分比的堆叠柱状图 graph bar percentage, over(race) over(age_group) by(cat_status_encoded, legend(col(1))) /// stack title("Cat Ownership Percentage by Race and Age Group") /// ytitle("Percentage") xtitle("Race and Age Group") /// blabel(bar, format(%4.1f) position(center) size(small))
Standard input is empty
// 清除之前的数据和变量 clear all // 输入数据 input str10 race str15 age_group owns_cat does_not_own_cat "White" "youth" 65 84 "White" "middle-aged" 92 107 "White" "elderly" 87 120 "Black" "youth" 4 14 "Black" "middle-aged" 3 17 "Black" "elderly" 4 15 "Other" "youth" 7 13 "Other" "middle-aged" 4 19 "Other" "elderly" 4 12 end // 计算每个组别的拥有猫和不拥有猫的百分比 gen total = owns_cat + does_not_own_cat gen owns_cat_percentage = (owns_cat / total) * 100 gen does_not_own_cat_percentage = (does_not_own_cat / total) * 100 // 重构数据为长格式 gen cat_status = "owns_cat" gen percentage = owns_cat_percentage tempfile temp save `temp', replace gen cat_status = "does_not_own_cat" gen percentage = does_not_own_cat_percentage append using `temp' // 将 cat_status 转换为标签变量 replace cat_status = "Owns Cats" if cat_status == "owns_cat" replace cat_status = "Does Not Own Cats" if cat_status == "does_not_own_cat" label define cat_status_lbl 1 "Owns Cats" 2 "Does Not Own Cats" encode cat_status, gen(cat_status_encoded) label values cat_status_encoded cat_status_lbl // 添加对应的数量 gen population = . replace population = owns_cat if cat_status == "Owns Cats" replace population = does_not_own_cat if cat_status == "Does Not Own Cats" // 绘制百分比的堆叠柱状图 graph bar percentage, over(race) over(age_group) by(cat_status_encoded, legend(col(1))) /// stack title("Cat Ownership Percentage by Race and Age Group") /// ytitle("Percentage") xtitle("Race and Age Group") /// blabel(bar, format(%4.1f) position(center) size(small))