// Prepare ESS round 8
use cntry essround wrkctra dweight using "ESS8e01.dta", clear
recode wrkctra (6 = .a) (7 = .b) (8 = .c) (9 = .d)
// Add ESS rounds 1-7
append using "ESS1-7e01.dta", keep(cntry essround wrkctr wrkctra dweight)
// Prepare variables
generate nocontract = (wrkctra == 3) if !missing(wrkctra)
kountry cntry, from(iso2c)
rename NAMES_STD country
// Prepare files for post commands
tempname foo1
tempname foo2
postfile `foo1' str20 country essround ll nocontract ul using `foo2', replace
qui levelsof country, local(country)
// Loop
foreach x of local country {
foreach i of numlist 1/8 {
capture logit nocontract [pw = dweight] if country == "`x'" & essround == `i'
if _rc == 0 {
qui margins [pw = dweight]
matrix prevs = r(table)
local prev = prevs[1,1] * 100
local ll = prevs[5,1] * 100
local ul = prevs[6,1] * 100
*di "`x'" _skip(5) `i' _skip(5) `ll' _skip(5) `prev' _skip(5) `ul'
post `foo1' ("`x'") (`i') (`ll') (`prev') (`ul')
}
}
}
postclose `foo1'
// Plot estimates
use `foo2', clear
// Fix value label
label define essround 1 "2002" 2 "2004" 3 "2006" 4 "2008" ///
5 "2010" 6 "2012" 7 "2014" 8 "2016", modify
label val essround essround
// First plot
sort country essround
twoway (rarea ll ul essround, lcolor(white)) ///
(connected nocontract essround), ///
by(country, ///
note("") ///
legend(off)) ///
xlabel(1/8, val ang(90)) ///
xtitle("") ytitle("% without job contract") ///
name(figure2a, replace) ysize(9)
// Second plot
reshape wide ll ul nocontract, i(country) j(essround)
scores average = mean(nocontract*)
egen order_ = rank(average), unique
labmask order_, value(country)
twoway (dot nocontract1 order_, horizontal) ///
(dot nocontract2 order_, horizontal) ///
(dot nocontract3 order_, horizontal) ///
(dot nocontract4 order_, horizontal) ///
(dot nocontract5 order_, horizontal) ///
(dot nocontract6 order_, horizontal) ///
(dot nocontract7 order_, horizontal) ///
(dot nocontract8 order_, horizontal) ///
(rspike ul1 ll1 order_, horizontal) ///
(rspike ul2 ll2 order_, horizontal) ///
(rspike ul3 ll3 order_, horizontal) ///
(rspike ul4 ll4 order_, horizontal) ///
(rspike ul5 ll5 order_, horizontal) ///
(rspike ul6 ll6 order_, horizontal) ///
(rspike ul7 ll7 order_, horizontal) ///
(rspike ul8 ll8 order_, horizontal), ///
ylabel(1/32, val) ytitle("") xscale(alt) ///
xtitle("% without job contract") ///
legend(order(1 "2002" 2 "2004" 3 "2006" 4 "2008" ///
5 "2010" 6 "2012" 7 "2014" 8 "2016") ///
pos(5) ring(0)) ///
name(figure2b, replace) ysize(9)
graph combine figure2a figure2b, ///
col(2) name(figure2, replace) ///
note(" " "{it:Source:} European Social Survey 2002-16, weighted data. {it:Note:} Error bands/spikes denote 95% confidence intervals", span size(*.7))
Showing posts with label twoway dot. Show all posts
Showing posts with label twoway dot. Show all posts
Nov 17, 2017
Random graphs (119): Line plots and dot plots
Labels:
European Social Survey,
foreach,
graph combine,
kountry,
labmask,
logit,
margins,
postfile,
Random graphs,
reshape,
scores,
twoway dot,
twoway rarea,
twoway rspike,
weight
Nov 16, 2017
Random graphs (118): Dot plot
clear
input str5 cntry eqls2003 eqls2007 ewcs2005 ewcs2010 eusilc2014
SE 0.021949 0.030043 0.00213 0.000918 .
FI 0.022075 0.013452 0.02246 0.011247 0.00012
HR . 0.018228 0.017975 0.013302 .
SK 0.011168 0.035384 0.013425 0.019773 0.003893
CZ 0.005486 0.064484 0.008917 0.005968 0.000863
NO . 0.0226 0.021383 0.018745 0.012686
CH . . 0.028731 . .
HU 0.018815 0.060927 0.044574 0.013885 0.019517
SI 0.025373 0.030885 0.095199 0.019257 0.001327
NL 0.035021 0.048701 0.021501 0.034217 .
BE 0.039831 0.088688 0.025436 0.006923 0.01386
EE 0.027082 0.048187 0.052969 0.052337 0.006435
FR 0.030219 0.074314 0.040906 0.01435 .
LT 0.049985 0.077502 0.05434 0.032847 0.006778
BG 0.037858 0.063697 0.065784 0.032313 0.039127
PL 0.023636 0.075742 0.06099 0.037228 .
LU 0.106816 0.102864 0.004992 0.006159 0.032854
DE 0.090262 0.040957 0.038157 0.035452 .
RO 0.063563 0.072842 0.070762 0.022769 .
LV 0.09474 0.077167 0.054927 0.034465 0.038258
IT 0.040173 0.128064 0.06421 0.036467 .
AT 0.057465 0.132496 0.095462 0.05458 .
ES 0.112064 0.127856 0.086716 0.076224 0.038867
DK 0.129036 0.103272 0.107504 0.040896 .
UK 0.120762 0.124342 0.150114 0.083238 0.024998
ME . . . 0.101533 .
PT 0.173582 0.179532 0.073722 0.113514 0.091105
RS-KM . . . 0.160115 .
MK . 0.194579 . 0.128292 .
IE 0.270422 0.359196 0.293468 0.240577 0.03082
AL . . . 0.275311 .
GR 0.404795 0.53023 0.286437 0.292037 0.144072
MT 0.302118 0.465496 0.387637 0.277371 .
CY 0.322423 0.54425 0.436497 0.395157 .
TR 0.564689 0.496668 0.689807 0.643683 .
end
scores average = mean(eqls2003 eqls2007 ewcs2005 ewcs2010)
kountry cntry, from(iso2c) marker
rename NAMES_STD country
replace country = "Kosovo" if country == "rskm"
egen order_ = rank(average), unique
labmask order_, value(country)
twoway (dot eqls2003 order_, horizontal) ///
(dot eqls2007 order_, horizontal) ///
(dot ewcs2005 order_, horizontal) ///
(dot ewcs2010 order_, horizontal) ///
(dot eusilc2014 order_, horizontal) ///
, ylabel(1/35, val) ysize(9) ///
ytitle("") xscale(alt) ///
xtitle("Proportion without job contract") ///
legend(order(1 "EQLS 2003" ///
2 "EQLS 2003" ///
3 "EWCS 2005" ///
4 "EWCS 2010" ///
5 "EU-SILC 2014") title("Data source") pos(5) ring(0))
Aug 12, 2017
Random graphs (109): Dropping one country at a time
// Open ESS 6 data
use stflife eduyrs agea gndr cntry using "ESS6e02_2.dta", clear
// Life satisfaction
recode stflife (77 88 99 = .), gen(lifesat)
// Education
sum eduyrs if eduyrs < 77, detail
generate education = eduyrs if eduyrs < 77
replace education = r(p99) if education >= r(p99) & !missing(education)
// Age
recode agea (999 = .), gen(age)
// Gender
generate female = (gndr == 2) if gndr != 9
// Fit model across all countries and save estimates
regress lifesat education c.age##c.age i.female, cluster(cntry)
local opointest = _b[education]
local olb = _b[education] - 1.96 * _se[education]
local oub = _b[education] + 1.96 * _se[education]
// Define temporary objects
tempname foo
tempname foox
postfile `foo' str3 cntry pointest lb ub using `foox', replace
// Drop one country at a time
levelsof cntry, local(country)
foreach i of local country {
qui regress lifesat education c.age##c.age i.female if cntry != "`i'"
local pointest = _b[education]
local lb = _b[education] - 1.96 * _se[education]
local ub = _b[education] + 1.96 * _se[education]
post `foo' ("`i'") (`pointest') (`lb') (`ub')
}
postclose `foo'
// Open estimates
use `foox', clear
// Creats country variable
kountry cntry, from(iso2c)
rename NAMES_STD geo
encode geo, generate(country)
label define country 29 "Kosovo", modify
// Plot estimates
sort country
twoway (rarea lb ub country, horizontal color(gs14)) ///
(function y = `opointest', horizontal range(country) lpattern(solid)) ///
(function y = `oub', horizontal range(country) lpattern(dash)) ///
(function y = `olb', horizontal range(country) lpattern(dash)) ///
(dot pointest country, horizontal) ///
, ylabel(1/29, val) ytitle("") xscale(alt) ///
legend(order(5 "Point estimate after excluding country" ///
2 "Point estimate from complete sample" ///
1 "95% CI after excluding country" ///
3 "95% CI (cluster robust) from complete sample") pos(6) span) ///
ysize(7) name(robustness, replace)
Feb 26, 2017
Chapter 2 of Singer and Willett's (2003) book on longitudinal data analysis
There is a different take on the chapter here, but I like mine better.
// Open data set use http://www.ats.ucla.edu/stat/stata/examples/alda/data/tolerance, clear // Figure 2.1 list, sep(0) noobs reshape long tol, i(id) j(age) list if inlist(id, 9, 45, 1653), sepby(id) noobs // Table 2.1 reshape wide quietly estpost cor tol*, matrix listwise esttab, unstack not noobs compress nostar b(%6.2f) // Figure 2.2
reshape long twoway (scatter tol age), by(id) ytitle(Tolerance) xtitle(Age) name(Figure22, replace) // Figure 2.3
twoway (scatter tol age) ///
(lowess tol age) ///
, by(id, note("Graphs by id, lowess curves") legend(off)) ///
ytitle(Tolerance) xtitle(Age) name(Figure23, replace)
// Table 2.2
preserve
tempfile table22
generate time = age - 11
statsby initial = _b[_cons] ///
initial_se = _se[_cons] ///
change = _b[time] ///
change_se = _se[time] ///
residual = (e(rmse)^2) ///
explained = e(r2) ///
, by(id) saving(`table22', replace): regress tol time
drop time
reshape wide
merge 1:1 id using `table22', nogenerate
format initial initial_se change change_se residual explained exposure %6.2f
keep id initial initial_se change change_se residual explained male exposure
order id initial initial_se change change_se residual explained male exposure
list, sep(0) noobs abbrev(15)
tempfile figure28
save `figure28', replace
// Figure 2.4
stem initial, round(.01)
stem change, round(.01)
stem residual, round(.01)
stem explained, round(.01)
restore
// Figure 2.5
twoway (scatter tol age) ///
(lfit tol age) ///
, by(id, note("Graphs by id, OLS curves") legend(off)) ///
ytitle(Tolerance) xtitle(Age) name(Figure25, replace)
// Figure 2.6
xtset id age
xtline tol, overlay t(age) i(id) legend(off) ///
ytitle(Tolerance) ylabel(1 (1) 4) ///
addplot(lowess tol age, lwidth(thick) lpattern(solid)) ///
xtitle(Age) title("Observed data and lowess smoother") ///
xsize(3) name(Figure26A, replace) nodraw
quietly regress tol i.id##c.age
predict tolhat
xtline tolhat, overlay t(age) i(id) legend(off) ///
ytitle(Tolerance) ylabel(1 (1) 4) ///
addplot(lfit tol age, lwidth(thick) lpattern(solid)) ///
xtitle(Age) title("OLS trajectories") ///
xsize(3) name(Figure26B, replace) nodraw
graph combine Figure26A Figure26B, col(2) name(Figure26, replace)
// Table 2.2
preserve
use `table22', clear
tabstat initial change, stat(mean sd) format(%6.2f)
cor initial change
restore
// Figure 2.7
quietly sum exposure, detail
generate highexposure = (exposure >= r(p50))
generate lowexposure = (exposure < r(p50))
generate female = !male
label var male "Males"
label var female "Females"
label var lowexposure "Low exposure"
label var highexposure "High exposure"
foreach z of varlist female male lowexposure highexposure {
capture drop tolhat
quietly regress tol i.id##c.age if `z'
predict tolhat if `z'
xtline tolhat if `z', ///
overlay t(age) i(id) legend(off) ///
ytitle("Predicted tolerance") ylabel(1 (1) 4) ///
addplot(lfit tol age if `z', lwidth(thick) lpattern(solid)) ///
xtitle(Age) title(`: variable label `z'') ///
xsize(3) ysize(2) name(Figure27_`z', replace) nodraw
}
graph combine Figure27_female Figure27_male Figure27_lowexposure Figure27_highexposure, col(2) name(Figure27, replace)
// Figure 2.8
use `figure28', clear
quietly correlate initial male
local pmca = round(r(rho), .01)
quietly correlate initial exposure
local pmcb = round(r(rho), .01)
quietly correlate change male
local pmcc = round(r(rho), .01)
quietly correlate change exposure
local pmcd = round(r(rho), .01)
label define male -1 " " 1 "Male" 0 "Female" 2 " ", modify
label val male male
twoway dot initial male, ///
ytitle("Predicted intercept") ///
xtitle("Gender") ///
xlabel(-1 0 1 2, val) ///
ysize(2) xsize(3) ///
note("{it:r} = `pmca'") ///
name(Figure28A, replace) nodraw
twoway scatter initial exposure, ///
ytitle("Predicted intercept") ///
xtitle("Exposure") ///
ysize(2) xsize(3) ///
note("{it:r} = `pmcb'") ///
name(Figure28B, replace) nodraw
twoway dot change male, ///
ytitle("Predicted change") ///
xtitle("Gender") ///
ysize(2) xsize(3) ///
xlabel(-1 0 1 2, val) ///
note("{it:r} = `pmcc'") ///
name(Figure28C, replace) nodraw
twoway scatter change exposure, ///
ytitle("Predicted change") ///
xtitle("Exposure") ///
ysize(2) xsize(3) ///
note("{it:r} = `pmcd'") ///
name(Figure28D, replace) nodraw
graph combine Figure28A Figure28B Figure28C Figure28D, col(2) row(2) name(Figure28, replace)
Reference
Singer, Judith D., and John B. Willett. 2003. Applied Longitudinal Data Analysis. Modeling Change and Event Occurrence. Oxford University Press. doi: 10.1093/acprof:oso/9780195152968.001.0001
Labels:
estpost,
reshape,
statsby,
Textbooks,
twoway dot,
twoway scatter,
xtline,
xtset
Apr 13, 2016
Random graphs (72): Dot plots with the by() option
clear
input str20 cntry bindirect blbindirect ulbindirect bdirect blbdirect ulbdirect
Austria 0.002 -0.002 0.005 0.008 -0.016 0.032
Germany 0.006 0.000 0.012 0.040 0.017 0.063
Sweden 0.001 -0.005 0.007 0.054 0.031 0.076
Netherlands 0.000 -0.006 0.006 0.039 0.017 0.061
Spain 0.005 0.002 0.009 0.016 -0.001 0.033
Italy 0.000 -0.005 0.005 0.029 0.011 0.047
France 0.001 -0.003 0.006 0.043 0.025 0.061
Denmark 0.001 0.000 0.003 0.015 0.001 0.029
Greece 0.000 -0.003 0.003 0.041 0.026 0.057
Switzerland 0.002 -0.002 0.006 0.003 -0.020 0.026
Belgium 0.000 -0.003 0.004 0.033 0.016 0.050
"Czech Republic" 0.004 -0.001 0.010 0.073 0.031 0.115
Poland -0.004 -0.010 0.002 0.034 -0.003 0.071
end
// Reshape to long format
reshape long b blb ulb, j(fx "indirect" "direct") i(cntry) string
// Encode variables
encode cntry, gen(country)
encode fx, gen(effect)
label define effect 1 "Direct effect" 2 "Indirect effect", modify
// Sort by biggest direct effect size
egen order_ = rank(b) if effect == 1, unique
labmask order_, val(country) decode
bysort country (order_): replace order_ = order_[1] // Copy value to all cases
// xrescale makes sure that x-axis fits both by() plots
twoway (dot b order_, horizontal by(effect, legend(off) note(" ") xrescale)) ///
(rspike blb ulb order_, horizontal by(effect)) ///
, ylabel(1 (1) 13, val) xscale(alt) ///
ytitle(" ") xline(0)
Apr 4, 2016
Random graphs (71): Proportions with confidence intervals
use sharew5_rel1-0-0_it.dta, clear
// Prepare variables
recode it004_ (1 = 1 "Yes") (5 = 0 "No") (-1 -2 . = .), generate(internetuser)
label var internetuser "Internet use in last 7 days"
decode country, gen(cntry)
// Define stuff
tempname foo
postfile `foo' str25 cntry perc perc_ll perc_ul using "C:\Windows\Temp\test.dta", replace
levelsof cntry, local(levels)
// Calculate proportions by country
foreach country of local levels {
capture proportion internetuser if cntry == "`country'"
matrix fcoefs = r(table)
local fperc = fcoefs[1,2] * 100
local fperc_ll = fcoefs[5,2] * 100
local fperc_ul = fcoefs[6,2] * 100
di "`country'" _skip(2) `fperc_ll' _skip(2) `fperc' _skip(2) `fperc_ul'
if "`fperc'" != "" { // Make sure that the loop doesn't break if empty
post `foo' ("`country'") (`fperc') (`fperc_ll') (`fperc_ul')
}
}
postclose `foo'
// Use posted data set
use "C:\Windows\Temp\test.dta", clear
// Sort countries by size
egen order_ = rank(perc), unique
labmask order_, value(cntry)
// Plot
twoway (dot perc order_, horizontal) ///
(rspike perc_ll perc_ul order_, horizontal), ///
ylabel(1/15, val) legend(off) xscale(range(20 80) alt) ///
ytitle("") xtitle("% Internet users (in last 7 days)") ///
xlabel(20(10)80, grid) ///
note(" " "{it:Source:} SHARE wave 5, doi:10.6103/SHARE.w5.100", span)
Mar 24, 2016
Random graphs (66): Dot plots with confidence intervals
clear
input str50 variable str4 data icc lb ub
"Overall" DE .46 .40 .53
"Overall" SE .49 .49 .50
"Overall" PSID .57 .55 .6
"Low father education" DE .42 .34 .5
"Low father education" SE .44 .43 .45
"Low father education" PSID .42 .31 .53
"High father education" DE .4 .29 .53
"High father education" SE .47 .46 .47
"High father education" PSID .58 .55 .62
"Low mother education" DE .45 .38 .53
"Low mother education" SE .45 .44 .46
"Low mother education" PSID .56 .53 .59
"High mother education" DE .33 .21 .48
"High mother education" SE .45 .44 .46
"High mother education" PSID .56 .53 .59
"Low parental occupation" DE .51 .43 .60
"Low parental occupation" SE .43 .42 .44
"Low parental occupation" PSID .59 .51 .67
"High parental occupation" DE .30 .21 .41
"High parental occupation" SE .39 .37 .40
"High parental occupation" PSID .54 .51 .57
"No migrant background" DE .40 .33 .49
"No migrant background" SE .48 .48 .49
"No migrant background" PSID .57 .53 .61
"Migrant background" DE .48 .35 .61
"Migrant background" SE .54 .52 .55
"Migrant background" PSID .56 .44 .68
"Family size 2-3 children" DE .48 .41 .54
"Family size 2-3 children" SE .48 .47 .48
"Family size 2-3 children" PSID . . .
"Family size 4 and more children" DE .31 .12 .61
"Family size 4 and more children" SE .55 .54 .56
"Family size 4 and more children" PSID . . .
end
generate indicator = 1 if variable == "Overall" & data == "DE"
replace indicator = 2 if variable == "Overall" & data == "SE"
replace indicator = 3 if variable == "Overall" & data == "PSID"
replace indicator = 4 if variable == "Low father education" & data == "DE"
replace indicator = 5 if variable == "Low father education" & data == "SE"
replace indicator = 6 if variable == "Low father education" & data == "PSID"
replace indicator = 7 if variable == "High father education" & data == "DE"
replace indicator = 8 if variable == "High father education" & data == "SE"
replace indicator = 9 if variable == "High father education" & data == "PSID"
replace indicator = 10 if variable == "Low mother education" & data == "DE"
replace indicator = 11 if variable == "Low mother education" & data == "SE"
replace indicator = 12 if variable == "Low mother education" & data == "PSID"
replace indicator = 13 if variable == "High mother education" & data == "DE"
replace indicator = 14 if variable == "High mother education" & data == "SE"
replace indicator = 15 if variable == "High mother education" & data == "PSID"
replace indicator = 16 if variable == "Low parental occupation" & data == "DE"
replace indicator = 17 if variable == "Low parental occupation" & data == "SE"
replace indicator = 18 if variable == "Low parental occupation" & data == "PSID"
replace indicator = 19 if variable == "High parental occupation" & data == "DE"
replace indicator = 20 if variable == "High parental occupation" & data == "SE"
replace indicator = 21 if variable == "High parental occupation" & data == "PSID"
replace indicator = 22 if variable == "No migrant background" & data == "DE"
replace indicator = 23 if variable == "No migrant background" & data == "SE"
replace indicator = 24 if variable == "No migrant background" & data == "PSID"
replace indicator = 25 if variable == "Migrant background" & data == "DE"
replace indicator = 26 if variable == "Migrant background" & data == "SE"
replace indicator = 27 if variable == "Migrant background" & data == "PSID"
replace indicator = 28 if variable == "Family size 2-3 children" & data == "DE"
replace indicator = 29 if variable == "Family size 2-3 children" & data == "SE"
replace indicator = 30 if variable == "Family size 2-3 children" & data == "PSID"
replace indicator = 31 if variable == "Family size 4 and more children" & data == "DE"
replace indicator = 32 if variable == "Family size 4 and more children" & data == "SE"
replace indicator = 33 if variable == "Family size 4 and more children" & data == "PSID"
label define indicator 1 "Overall" ///
4 "Low father education" ///
7 "High father education" ///
10 "Low mother education" ///
13 "High mother education" ///
16 "Low parental occupation" ///
19 "High parental occupation" ///
22 "No migrant background" ///
25 "Migrant background" ///
28 "Family size 2-3 children" ///
31 "Family size 4 and more children"
label val indicator indicator
twoway (dot icc indicator if data == "DE", horizontal msymbol(o)) ///
(rspike ub lb indicator if data == "DE", horizontal) ///
(dot icc indicator if data == "SE", horizontal msymbol(t)) ///
(rspike ub lb indicator if data == "SE", horizontal) ///
(dot icc indicator if data == "PSID", horizontal msymbol(s)) ///
(rspike ub lb indicator if data == "PSID", horizontal) ///
, legend(order(1 "Germany" 3 "Sweden" 5 "United States (PSID)") pos(2)) ///
yscale(reverse) ylabel(1 (3) 31, val) ///
xscale(alt) ytitle("") xtitle("Sibling correlations in cognitive skills") ///
note("{it:Note:} Germany: {it:N} = 1,989 individuals in 1,431 families" ///
"Sweden: {it:N} = 652,940 individuals in 536,224 families" ///
"United States: {it:N} = 2,868 individuals in 1,968 families" , span)
Labels:
Random graphs,
twoway dot,
twoway rspike
Feb 25, 2016
Random graphs (61): Dot plot for two groups
tempname foo
tempname foox
postfile `foo' str2 cntry perc_f perc_f_ll perc_f_ul ///
perc_m perc_m_ll perc_m_ul using `foox' , replace
levelsof cntry, local(levels1)
// Calculate proportions by country
foreach country of local levels1 {
capture proportion nonesep_f if cntry == "`country'"
*matrix list r(table)
matrix fcoefs = r(table)
local fperc = fcoefs[1,2] * 100
local fperc_ll = fcoefs[5,2] * 100
local fperc_ul = fcoefs[6,2] * 100
capture proportion nonesep_m if cntry == "`country'"
*matrix list r(table)
matrix mcoefs = r(table)
local mperc = mcoefs[1,2] * 100
local mperc_ll = mcoefs[5,2] * 100
local mperc_ul = mcoefs[6,2] * 100
di "`country'" _skip(2) `fperc_ll' _skip(2) `fperc' _skip(2) `fperc_ul'
di "`country'" _skip(2) `mperc_ll' _skip(2) `mperc' _skip(2) `mperc_ul'
if "`fperc'" != "" { // Make sure that the loop doesn't break if empty
post `foo' ("`country'") (`fperc') (`fperc_ll') (`fperc_ul') (`mperc') (`mperc_ll') (`mperc_ul')
}
}
postclose `foo'
// Use posted data set
use `foox', clear
// Reverse sign of one variable
replace perc_m = -perc_m
replace perc_m_ll = -perc_m_ll
replace perc_m_ul = -perc_m_ul
// Sort countries by size
egen order_ = rank(-perc_f), unique
labmask order_, value(cntry)
// Plot
twoway (dot perc_m order_, horizontal) ///
(dot perc_f order_, horizontal) ///
, ylabel(1/31, val) legend(order(1 "Men" 2 "Women") pos(6) row(1)) ///
ytitle("") xtitle("% of men/women pooling all income") ///
xline(0) ///
xlabel(-100 "100" -50 "50" 0 "0" 50 "50" 100 "100") ///
name(somefigure, replace) ysize(8)
Jan 30, 2016
Random graphs (56): Intraclass Correlation Coefficients with confidence intervals
webuse productivity, clear
tempname foo
postfile `foo' str100 commandline_str str100 description_str icc icclb iccub N N_groups using "C:\Windows\Temp\test.dta", replace
qui mixed gsp || region: if year <= 1973
qui estat icc
matrix groups = e(N_g)
scalar n_g = groups[1,1]
matrix cis = r(ci2)
scalar icclb = cis[1,1]
scalar iccub = cis[1,2]
local desc "ICC 1970 to 1973"
post `foo' (e(cmdline)) ("`desc'") (r(icc2)) (icclb) (iccub) (e(N)) (n_g)
qui mixed gsp || region: if year >= 1974 | year <= 1977
qui estat icc
matrix groups = e(N_g)
scalar n_g = groups[1,1]
matrix cis = r(ci2)
scalar icclb = cis[1,1]
scalar iccub = cis[1,2]
local desc "ICC 1974 to 1977"
post `foo' (e(cmdline)) ("`desc'") (r(icc2)) (icclb) (iccub) (e(N)) (n_g)
qui mixed gsp || region: if year >= 1978 | year <= 1981
qui estat icc
matrix groups = e(N_g)
scalar n_g = groups[1,1]
matrix cis = r(ci2)
scalar icclb = cis[1,1]
scalar iccub = cis[1,2]
local desc "ICC 1978 to 1981"
post `foo' (e(cmdline)) ("`desc'") (r(icc2)) (icclb) (iccub) (e(N)) (n_g)
qui mixed gsp || region: if year >= 1981 | year <= 1984
qui estat icc
matrix groups = e(N_g)
scalar n_g = groups[1,1]
matrix cis = r(ci2)
scalar icclb = cis[1,1]
scalar iccub = cis[1,2]
local desc "ICC 1981 to 1984"
post `foo' (e(cmdline)) ("`desc'") (r(icc2)) (icclb) (iccub) (e(N)) (n_g)
qui mixed gsp || region: if year >= 1985 | year <= 1986
qui estat icc
matrix groups = e(N_g)
scalar n_g = groups[1,1]
matrix cis = r(ci2)
scalar icclb = cis[1,1]
scalar iccub = cis[1,2]
local desc "ICC 1985 to 1986"
post `foo' (e(cmdline)) ("`desc'") (r(icc2)) (icclb) (iccub) (e(N)) (n_g)
postclose `foo'
use "C:\Windows\Temp\test.dta", clear
list
encode description_str, gen(description)
twoway (dot icc description, horizontal) ///
(rcap icclb iccub description, horizontal) ///
, ylabel(1/5, val) ytitle("") legend(off) ///
xlabel(0 (.1) 1) xtitle("ICC") name(figure, replace)
erase "C:\Windows\Temp\test.dta"
Labels:
estat icc,
ICC,
local,
matrix,
mixed,
Multilevel modeling,
postfile,
Random graphs,
scalar,
twoway dot,
twoway rcap,
xtmixed postestimation
Aug 18, 2015
Random Graphs (50): Dot graphs with confidence intervals
// Create temporary object
tempname bqlrer
// Define postfile
postfile `bqlrer' count str100 commandline str100 descri str10 entity ///
prev prev_loci prev_hici differ differ_loci differ_hici ///
loed mide hied ratio_ ratio_loci ratio_hici n ///
using "results\results", replace
// Count variable
local count = 0
// Levels for loop
levelsof entity, local(entity_levels)
*di `entity_levels'
// Loop: 1 round per entity
foreach Y of local entity_levels {
local entity_level = "`Y'"
di "`entity_level'"
*qui sum poorhealth if entity == "`Y'"
*scalar proportion = r(mean)
// Model 1: OV: PSRH lowest2, adjusted -- Prevalence rate only, education not in model
qui logit poorhealth c_age c_female if entity == "`Y'"
di _rc
if _rc == 0 {
*prev prev_loci prev_hici
qui margins if entity == "`Y'", post
scalar prev = 100 * _b[_cons]
scalar prev_loci = 100 * (_b[_cons] - 1.96 * _se[_cons])
scalar prev_hici = 100 * (_b[_cons] + 1.96 * _se[_cons])
di `prev'
di `prev_loci'
di `prev_hici'
}
// Model 2: OV: PSRH lowest2, adjusted
local count = `count' + 1
local desc "DV: Poor health (bottom 2), IV: Education, Age, Sex"
qui logit poorhealth i.education c_age c_female if entity == "`Y'"
local commandline = e(cmdline)
di _rc
if _rc == 0 {
// Differences Model 2
qui margins r.education if entity == "`Y'"
scalar differ = -10 * _b[r3vs1.education]
scalar differ_loci = -10 * (_b[r3vs1.education] + (1.96 * _se[r3vs1.education]))
scalar differ_hici = -10 * (_b[r3vs1.education] - (1.96 * _se[r3vs1.education]))
// Predicted probabilities Model 2
qui margins i.education if entity == "`Y'", post
matrix preds = r(table)
scalar loed = preds[1,1]
scalar mide = preds[1,2]
scalar hied = preds[1,3]
matrix drop preds
// Ratios Model 2
qui nlcom _b[1.education]/_b[3.education], post
scalar ratio_ = _b[_nl_1]
scalar ratio_loci = _b[_nl_1] - 1.96 * _se[_nl_1]
scalar ratio_hici = _b[_nl_1] + 1.96 * _se[_nl_1]
}
else {
scalar differ = -99
scalar differ_loci = -99
scalar differ_hici = -99
scalar ratio_ = -99
scalar ratio_loci = -99
scalar ratio_hici = -99
scalar loed = -99
scalar mide = -99
scalar hied = -99
}
post `bqlrer' (`count') (`"`commandline'"') ("`desc'") ("`Y'") ///
(prev) (prev_loci) (prev_hici) ///
(differ) (differ_loci) (differ_hici) ///
(loed) (mide) (hied) ///
(ratio_) (ratio_loci) (ratio_hici) (e(N))
}
// Fit one model for entire EVS
// Model 1: OV: PSRH lowest2, adjusted -- Prevalence rate only, education not in model
qui logit poorhealth c_age c_female [pw = eu_weight] if survey == "EVS"
qui margins if survey == "EVS", post
scalar prev = 100 * _b[_cons]
scalar prev_loci = 100 * (_b[_cons] - 1.96 * _se[_cons])
scalar prev_hici = 100 * (_b[_cons] + 1.96 * _se[_cons])
di `prev'
di `prev_loci'
di `prev_hici'
// Model 2: OV: PSRH lowest2, adjusted
local count = `count' + 1
local desc "DV: Poor health (bottom 2), IV: Education, Age, Sex"
qui logit poorhealth i.education c_age c_female /*[pw = eu_weight]*/ if survey == "EVS"
local commandline = e(cmdline)
// Differences Model 2
qui margins r.education if survey == "EVS"
scalar differ = -10 * _b[r3vs1.education]
scalar differ_loci = -10 * (_b[r3vs1.education] + (1.96 * _se[r3vs1.education]))
scalar differ_hici = -10 * (_b[r3vs1.education] - (1.96 * _se[r3vs1.education]))
// Predicted probabilities Model 2
qui margins i.education if survey == "EVS", post
matrix preds = r(table)
scalar loed = preds[1,1]
scalar mide = preds[1,2]
scalar hied = preds[1,3]
matrix drop preds
// Ratios Model 2
qui nlcom _b[1.education]/_b[3.education], post
scalar ratio_ = _b[_nl_1]
scalar ratio_loci = _b[_nl_1] - 1.96 * _se[_nl_1]
scalar ratio_hici = _b[_nl_1] + 1.96 * _se[_nl_1]
local Y = "EVS"
post `bqlrer' (`count') (`"`commandline'"') ("`desc'") ("`Y'") ///
(prev) (prev_loci) (prev_hici) ///
(differ) (differ_loci) (differ_hici) ///
(loed) (mide) (hied) ///
(ratio_) (ratio_loci) (ratio_hici) (e(N))
postclose `bqlrer'
// Create data set with FIPS codes and state names
preserve
tempfile codescheme
egen pickone = tag(entity)
keep if pickone
keep entity entity_num
save `codescheme'
restore
// Merge FIPS codes to results
use results\results, clear
merge 1:1 entity using `codescheme', keepusing(entity entity_num)
drop _merge
label var count "Generic counter"
label var commandline "Command line"
label var descri "Description of model fitted"
label var entity "Entity (string)"
label var prev "Proportion poor health"
label var prev_loci "Proportion 95 % CI (lower)"
label var prev_hici "Proportion 95 % CI (higher)"
label var loed "Proportion poor health lower educ."
label var mide "Proportion poor health mid educ."
label var hied "Proportion poor health higher educ."
label var differ "Difference lower educated - higher"
label var differ_loci "Difference 95 % CI (lower)"
label var differ_hici "Difference 95 % CI (higher)"
label var ratio_ "Ratio lower educated / higher"
label var ratio_loci "Ratio 95 % CI (lower)"
label var ratio_hici "Ratio 95 % CI (higher)"
label var n "Size of entity sample"
// Save results, also as csv-file
save results\results, replace
outsheet using "results\results.csv", comma replace nolabel
use results\results, replace
// Create US identifier
gen usa = 0
replace usa = 1 if regexm(entity, "US-")
replace entity = "{bf:Europe}" if entity == "EVS"
egen order_ratio = rank(-ratio_), unique
labmask order_ratio, value(entity)
egen order_differ = rank(-differ), unique
labmask order_differ, value(entity)
egen order_prev = rank(-prev), unique
labmask order_prev, value(entity)
twoway (dot prev order_prev if usa == 0, horizontal ndots(20)) ///
(dot prev order_prev if usa == 1, horizontal ndots(20)) ///
(rspike prev_loci prev_hici order_prev, horizontal) ///
, ///
legend(label(1 "Europe") label(2 "US") label(3 "95% CI") pos(1) ring(0)) ///
ylabel(1/97, valuelabels ang(h) labsize(*.65)) ///
ytitle("") ///
xtitle("Prevalence poor health") ///
name(prevalence, replace) ///
xsize(2.7) ysize(10)
generate ratio_loci_p = ratio_loci // Shorten CI's to make graph fit better
replace ratio_loci_p = 0 if ratio_loci_p < 0
generate ratio_hici_p = ratio_hici
replace ratio_hici_p = 6 if ratio_hici_p > 6
twoway (dot ratio_ order_ratio if usa == 0, horizontal ndots(20) msymbol(smplus)) ///
(dot ratio_ order_ratio if usa == 1, horizontal ndots(20) msymbol(smx)) ///
(rspike ratio_loci_p ratio_hici_p order_ratio, horizontal) ///
, ///
legend(label(1 "Europe") label(2 "US") label(3 "95 % CI") pos(1) ring(0)) ///
ylabel(1/97, valuelabels ang(h) labsize(*.65)) ///
xscale(range(0 6)) xlabel(0 1 3 5) ///
ytitle("") ///
xtitle("Relative" "inequalities") ///
xline(1) ///
xline(1.81019, lpattern(dash)) ///
name(relative, replace) ///
xsize(2.7) ysize(10)
generate differ_loci_p = differ_loci // Shorten CI's to make graph fit better
replace differ_loci_p = -1 if differ_loci_p < -1
twoway (dot differ order_differ if usa == 0, horizontal ndots(20) msymbol(smplus)) ///
(dot differ order_differ if usa == 1, horizontal ndots(20) msymbol(smx)) ///
(rspike differ_loci_p differ_hici order_differ, horizontal) ///
, ///
legend(label(1 "Europe") label(2 "US") label(3 "95 % CI") pos(1) ring(0)) ///
xscale(range(0 30)) xlabel(0(10)30) ///
ylabel(1/97, valuelabels ang(h) labsize(*.65)) ///
ytitle("") ///
xtitle("Absolute" "inequalities") ///
xline(6.8754, lpattern(dash)) ///
name(absolute, replace) ///
xsize(2.7) ysize(10)
twoway (dot prev order_prev if usa == 0, horizontal ndots(20) msymbol(smplus)) ///
(dot prev order_prev if usa == 1, horizontal ndots(20) msymbol(smx)) ///
(rspike prev_loci prev_hici order_prev, horizontal) ///
, ///
legend(label(1 "Europe") label(2 "US") label(3 "95% CI") row(1) pos(12) size(vsmall) region(lwidth(vthin) lcolor(black)) bmargin(tiny) colgap(*.3)) ///
ylabel(1/97, valuelabels ang(h) labsize(*.65)) ///
ytitle("") ///
xtitle("Prevalence" "poor health") ///
xline(11.26938, lpattern(dash)) ///
name(prevalence_leg, replace) ///
xsize(2.7) ysize(10)
// 8.27 × 11.69
*graph combine prevalence absolute relative, xsize(8.27) ysize(10) col(3) name(comb, replace)
grc1leg prevalence_leg absolute relative, xsize(8.27) ysize(10) col(3) imargin(small) legendfrom(prevalence_leg) name(oneleg, replace) pos(6) span // ignores size-commands
graph display oneleg, xsize(6.27) ysize(9.69) // Thus redraw so that size commands take effect
Apr 20, 2015
Random graphs (45): Re-creating -graph dot- using -twoway dot-

This plot recreates this one, but adds confidence intervals.
preserve
// Calculate country-specific means to be plotted
tempname foo
tempname idealage
postfile `foo' quintile incocomp incocomp_lb incocomp_ub using `foo2', replace
levelsof(quintile), local(quintile)
foreach x of local quintile {
qui reg incocomp if quintile == `x', cluster(cntry)
local incocomp = _b[_cons]
local incocomplb = _b[_cons] - (1.96 * _se[_cons])
local incocompub = _b[_cons] + (1.96 * _se[_cons])
post `foo' (`x') (`incocomp') (`incocomplb') (`incocompub')
}
postclose `foo'
// Plot country-specific means
use `foo2', clear
twoway (dot incocomp quintile) /// -twoway scatter- doesn't have the lines
(rcap incocomp_lb incocomp_ub quintile) ///
, yscale(range(1.5 3.0)) ///
ylabel(1.5 (.25) 3.0, format(%6.2f)) ///
legend(off)
title("Income quintiles")
xlabel(1 `""1" "(poorest)""' /// Double-compound quotes allow for the line break
2 3 4 5 `""5" "(richest)"') ///
fxsize(40) /// Forces x-size to be 40 percent of its original size
xtitle("") ///
xscale(range(0.2 5.8)) /// Making this a bit bigger makes room for the labels
name(byquintile_hor, replace)
restore
// Calculate country-specific means to be plotted 2
preserve
tempname foo
tempname idealage
postfile `foo' str2 cntry incocomp incocomp_lb incocomp_ub using `foo2', replace
levelsof(cntry), local(cntry)
foreach x of local cntry {
qui reg incocomp if cntry == "`x'"
local incocomp = _b[_cons]
local incocomplb = _b[_cons] - (1.96 * _se[_cons])
local incocompub = _b[_cons] + (1.96 * _se[_cons])
post `foo' ("`x'") (`incocomp') (`incocomplb') (`incocompub')
}
postclose `foo'
use `foo2', clear
// Create sorted-by-size variable
egen order_ = rank(-incocomp), unique
labmask order_, value(cntry)
// Plot country-specific means 2
twoway (dot incocomp order_) ///
(rcap incocomp_lb incocomp_ub order_) ///
, yscale(off) /// Not necessary, as we're using the one from the other graph
xlabel(1/23, val alt) ///
title("Countries") ///
xtitle("") ///
legend(off) ///
/* graphregion(margin(b=16)) */ /// Could help as -ycommon- isn't accounting for the different label sizes
name(bycntry_hor, replace)
// Combine plots
graph combine byquintile_hor bycntry_hor, ///
l1title("Mean income comparison orientation") ///
ycommon row(1) ///
imargin(zero) // Sets margin between both plots to 0
restore
Nov 30, 2014
Random graphs (37): Proportions with confidence intervals
use acountry asex aage ayear a602 a612 aweight using GGS_Wave1_V.4.2.dta, clear // Create outcome variable recode a612 (1 2 1601 = 1 "(Likely) infertile") /// (3 4 1501 1602 = 0 "(Likely) fertile") /// (2001 . .a .b .c = .x "Don't know"), /// gen(infertility) replace infertility = 0 if a602 == 1 // Also fertile when currently pregnant // Create country identifier gen cntry = "" replace cntry = "BG" if acountry == 11 replace cntry = "RU" if acountry == 12 replace cntry = "GE" if acountry == 13 replace cntry = "DE" if acountry == 14 replace cntry = "FR" if acountry == 15 replace cntry = "HU" if acountry == 16 replace cntry = "IT" if acountry == 17 replace cntry = "NL" if acountry == 18 replace cntry = "RO" if acountry == 19 replace cntry = "NO" if acountry == 20 replace cntry = "AT" if acountry == 21 replace cntry = "EE" if acountry == 22 replace cntry = "BE" if acountry == 23 replace cntry = "AU" if acountry == 24 replace cntry = "LT" if acountry == 25 replace cntry = "PL" if acountry == 26 replace cntry = "CZ" if acountry == 28 // Recode gender variable gen sex = "" replace sex = "Men" if asex == 1 replace sex = "Women" if asex == 2 // Drop unnecessary countries drop if inlist(cntry, "IT", "AU", "NL") // Prevalence plot by country preserve // Drop unnecesary age groups keep if aage <= 39 keep if aage >= 34 svyset [pweight = aweight] // Declare weight // Create temporary files and postfile tempname foo tempname infert postfile `foo' str2 cntry str5 sex perc_infert perc_infert_ll perc_infert_ul using `infert' , replace levelsof cntry, local(levels1) levelsof sex, local(sex1) // Calculate proportions by country and sex foreach sex of local sex1 { foreach country of local levels1 { // Calculate proportions capture proportion infertility if cntry == "`country'" & sex == "`sex'" *matrix list r(table) matrix coefs = r(table) local perc = coefs[1,2] * 100 local perc_ll = coefs[5,2] * 100 local perc_ul = coefs[6,2] * 100 di "`country'" _skip(2) `perc_ll' _skip(2) `perc' _skip(2) `perc_ul' if "`perc'" != "" { // Make sure that the loop doesn't break if empty post `foo' ("`country'") ("`sex'") (`perc') (`perc_ll') (`perc_ul') } } } postclose `foo' // Use posted data set use `infert', clear // Sort countries by size for women egen order_ = rank(-perc_infert) if sex == "Women", unique labmask order_, value(cntry) // Plot for women twoway (dot perc_infert order_ if sex == "Women", horizontal) /// (rcap perc_infert_ll perc_infert_ul order_ if sex == "Women", horizontal) /// , ylabel(1/14, val) legend(off) /// ytitle("") xtitle("% of {bf:women} aged 35{c 0150}39 reporting (suspected) infertility") /// /*caption("{it:Note:} Error bars denote 95 % confidence intervals", size(small) span)*/ /// name(infert3539women, replace) // Drop women's order drop order_ // Sort countries by size for men egen order_ = rank(-perc_infert) if sex == "Men", unique labmask order_, value(cntry) // Plot for men twoway (dot perc_infert order_ if sex == "Men", horizontal) /// (rcap perc_infert_ll perc_infert_ul order_ if sex == "Men", horizontal) /// , ylabel(1/13, val) legend(off) /// ytitle("") xtitle("% of {bf:men} aged 35{c 0150}39 reporting (suspected) infertility") /// /*caption("{it:Note:} Error bars denote 95 % confidence intervals", size(small) span)*/ /// name(infert3539men, replace) // Combine graphs graph combine infert3539women infert3539men /// , ysize(8) col(1) xcommon /// caption("{it:Source:} Generations and Gender Survey Wave 1 (2005{c 0150}2011}" /// "{it:Note:} Error bars denote 95 % confidence intervals", size(vsmall) span) restore // Plot infertility by age // Recode age into groups recode aage (20/24 = 1 "20–24") /// (25/29 = 2 "25–29") /// (30/34 = 3 "30–34") /// (35/39 = 4 "35–39") /// (40/45 = 5 "40–45") /// (1/19 = .a "Below 20 y") /// (46/85 = .b "46+ y") /// , gen(age) // Save valuelabels in temporary do-file tempfile valuelabels label save age using `valuelabels' svyset [pweight = aweight] // Declare weight // Create temporary files and postfile tempname foo tempname infertage postfile `foo' str2 cntry str5 sex age perc_infert perc_infert_ll perc_infert_ul using `infertage' , replace levelsof cntry, local(levels1) levelsof sex, local(sex1) // Calculate proportion by age group, country, and sex foreach sex of local sex1 { foreach country of local levels1 { forvalues x = 1/5 { // Calculate proportions capture proportion infertility if age == `x' & cntry == "`country'" & sex == "`sex'" *matrix list r(table) matrix coefs = r(table) local perc = coefs[1,2] * 100 local perc_ll = coefs[5,2] * 100 local perc_ul = coefs[6,2] * 100 di "`country'" _skip(2) `x' _skip(2) `perc_ll' _skip(2) `perc' _skip(2) `perc_ul' if "`perc'" != "" { // Make sure that the loop doesn't break if post `foo' ("`country'") ("`sex'") (`x') (`perc') (`perc_ll') (`perc_ul') } } } } postclose `foo' // Use posted values use `infertage', clear drop if perc_infert == . // Drop empty rows // Define and set saved value labels again do `valuelabels' label val age age // Plot for women by country and age twoway (rarea perc_infert_ll perc_infert_ul age if sex == "Women", fcolor(gs15) cmissing(no)) /// (line perc_infert age if sex == "Women", cmissing(no)) /// , by(cntry, cols(3) legend(off) note("") /// caption("{it:Source:} Generations and Gender Survey Wave 1 (2005{c 0150}2011)" /// "{it:Note:} Gray areas denote 95 % confidence intervals", size(vsmall) span)) /// ytitle("% of {bf:women} reporting (suspected) infertility") xtitle("Age group") /// xlabel(1/5, val alternate) /// ysize(8) name(infertage, replace)
Oct 15, 2014
Random graphs (33): Regression parameters
use V4 V56 SEX using "ZA5900_v2-0-0.dta", replace // ISSP 2012 data
renvars, lower // Switch variable names to lower case
kountry v4, from(iso3n) to(iso2c) // Generate country abbreviation variable
replace _ISO2C_ = "RU" if v4 == 643
encode _ISO2C_, gen(country)
drop if cntry == "ZA" // v56 missing in ZA
// Prepare variables
recode sex (9 = .)
recode v56 (0 8 9 = .), gen(jobsat_rev)
generate jobsat = 7 - jobsat_rev
label define jobsat 6 "Completely satisfied" ///
3 "Neither satisfied nor dissatisfied" ///
0 "Completely dissatisfied"
label value jobsat jobsat
preserve
// Save parameters
statsby gendergap = _b[sex] ///
loci = (_b[sex] - 1.96 * _se[sex]) ///
hici = (_b[sex] + 1.96 * _se[sex]) ///
, by(country) clear total: ///
regress jobsat sex
replace country = 1000 if country == . // Label parameter from total sample
label define country 1000 "{bf: Total}", modify // Label parameter from total sample
egen order_ = rank(-gendergap), unique
labmask order_, value(country) decode
twoway (dot gendergap order_, msize(vsmall)) ///
(rcap loci hici order_) ///
, legend(off) xlabel(1/37, valuelabels ang(v)) ///
yline(0) note("{it:Source:} ISSP 2012 (Family and Changing Gender Roles IV), own calculations", span) ///
ylabel(,format(%6.1f)) name(gendergap, replace) ///
xtitle(" ") ytitle("Gender gap in job satisfaction")
restore
Oct 7, 2014
Random graphs (32): Dot plot with confidence intervals
// Read in data points
input str50 variable_str coeff se
"Discrimination in being hired" .18 .08
"Vocational index" 1.97 .53
end
// Switch to numeric
encode variable_str, gen(variable)
// Create variable for -by-
recode variable (1 = 2 "Model 2") (2 = 1 "Model 1"), gen(model)
// Calculate 95 % CI's
gen loci = coeff - 1.96 * se
gen hici = coeff + 1.96 * se
twoway (dot coeff variable, by(model, legend(off) note("")) ///
horizontal dotextend(no)) ///
(rcap hici loci variable, horizontal) ///
, legend(off) ylabel(1/2, valuelabels) ///
xline(0) ytitle("") ///
ysize(4) yscale(range(0 3))
Labels:
Confidence intervals,
Random graphs,
twoway dot,
twoway rcap
Jun 20, 2014
Random graphs (26): Plot means by country
use cntry stflife using "ESS1e06.3_F1.dta", clear
encode cntry, gen(country) // De-string country identifier
preserve
statsby mean_ = _b[_cons] ///
loci = (_b[_cons] - 1.96 * _se[_cons]) ///
hici = (_b[_cons] + 1.96 * _se[_cons]) ///
, by(country) total clear: /// // -total- fits model for total sample
regress stflife
replace country = 1000 if country == . // Label mean from total sample
label define country 1000 "{bf: Total}", modify // Label mean from total sample
egen order_ = rank(-mean_), unique
labmask order_, value(country) decode
twoway (dot mean_ order_, msize(vsmall)) ///
(rcap loci hici order_) ///
, legend(off) xlabel(1/23, valuelabels ang(v)) ///
ylabel(,format(%6.1f)) name(lifesat, replace) ///
xtitle("") ytitle("Life satisfaction (avg.)")
restore
Jun 2, 2014
Random graphs (21): Confidence interval plots
clear
input str33 fiel prop_women prop_women_se ci_low ci_hi str3 test_
"Education" 0.7365 0.0029 0.7308 0.7422 No
"Social and behavioral sciences" 0.5251 0.0163 0.4931 0.5569 Yes
"Psychology" 0.8282 0.0183 0.7921 0.8639 No
"Nursing and caring" 0.9298 0.0046 0.9208 0.9388 No
"Therapy and rehabilitation" 0.8598 0.0336 0.7939 0.9257 No
"Child care and youth service" 0.9517 0.0178 0.9168 0.9866 No
"Social work and counseling" 0.8419 0.0238 0.7953 0.8885 No
end
// Transform from proportion to percentage
replace prop_women = prop_women * 100
replace ci_low = ci_low * 100
replace ci_hi = ci_hi * 100
// Sort educational fields by % females
egen order_ = rank(-prop_women), unique
labmask order_, val(fiel)
twoway (dot prop_women order_, horizontal) ///
(rcap ci_low ci_hi order_, horizontal) ///
, legend(off) ylabel(1/7, valuelabels) ///
ytitle("Educational fields") ///
xtitle("% Females") ///
xline(50) xlabel(40 (10) 100, format(%6.0f)) ///
note("{it: Source:} European Labor Force Survey 2009" ///
"{it: Note:} Error bars denote 95% CI's", span)
clear
input str44 fiel prop_women prop_women_se ci_low ci_hi hard
"Science, mathematics, and computing" 0.445 0.0114 0.4226 0.4673 1
"Physical science" 0.383 0.0069 0.3694 0.3964 1
"Physics" 0.390 0.0288 0.3336 0.4464 1
"Mathematics" 0.571 0.0193 0.5331 0.6089 1
"Computer science" 0.252 0.0051 0.1460 0.3580 1
"Engineering, manufacturing, and construction" 0.161 0.0012 0.1586 0.1634 1
"Engineering and engineering trades" 0.199 0.0182 0.1633 0.2347 1
"Humanities" 0.717 0.0096 0.698 0.7358 0
"Social and behavioral science" 0.525 0.0163 0.4931 0.5569 0
"Psychology" 0.828 0.0183 0.7921 0.8639 0
"Sociology and cultural studies" 0.663 0.0354 0.5936 0.7323 0
end
// Transform from proportion to percentage
replace prop_women = prop_women * 100
replace ci_low = ci_low * 100
replace ci_hi = ci_hi * 100
// Sort educational fields by % females and by hard/soft
egen orderhard = rank(-prop_women) if hard, unique
labmask orderhard, val(fiel)
egen ordersoft = rank(-prop_women) if hard == 0, unique
labmask ordersoft, val(fiel)
twoway (dot prop_women orderhard, horizontal) ///
(rcap ci_low ci_hi orderhard, horizontal) ///
, legend(off) ylabel(1/7, valuelabels) ///
ytitle("Hard educational fields") ///
xtitle("% Females") ///
xline(50) xlabel(20 (10) 100, format(%6.0f)) ///
xscale(off) /// // remove x-axis
name(hard, replace)
twoway (dot prop_women ordersoft, horizontal) ///
(rcap ci_low ci_hi ordersoft, horizontal) ///
, legend(off) ylabel(1/4, valuelabels) ///
ytitle("Soft educational fields") ///
xtitle("% Females") ///
graphregion(margin(l=28)) /// Account for different y-axis label length
xline(50) xlabel(20 (10) 100, format(%6.0f)) ///
name(soft, replace)
graph combine hard soft, col(1) imargin(b = 2 t = 1) ///
note("{it: Source:} European Labor Force Survey 2009" ///
"{it: Note:} Error bars denote 95% CI's", span)
graph export Graph.png
May 28, 2014
Calculate coefficient alpha by country
use "ZA5900_v1-0-0.dta", replace
renvars, lower // Switch variable names to lower case
kountry v4, from(iso3n) to(iso2c) // Generate country abbreviation variable
encode _ISO2C_, gen(country)
fre v51-v54 // Work-family conflict items
// Factor analysis yields one-dimensional solution:
factor v51-v54, pcf
// Calculate Cronbach's alpha for each country of the sample:
preserve
statsby alpha_ = r(alpha) ///
, by(country) clear total: /// -total- adds row for total sample
alpha v51-v54
replace country = 25 if country == . // Label row for total sample
label define country 25 "All", modify // Label row for total sample
sort alpha_ // Make list
list, sep(0)
// Create graph
egen order_ = rank(-alpha_), unique
labmask order_, value(country) decode
twoway (dot alpha_ order_) ///
, yline(.70) ///
xlab(1/25, valuelabels ang(v)) xtitle("Country") ///
ylabel(, format(%6.2f)) ytitle("Cronbach's alpha of work{c 150}family conflict scale") ///
note("{it: Note:} Horizontal line denotes conventional cut-off value for Cronbach's alpha", span)
restore
Oct 8, 2013
Random graphs (16): Plots with confidence intervals
preserve
reg srh i.country [pweight = weight]
predict means, xb
predict semeans, stdp
gen loci = means - 1.96 * semeans
gen hici = means + 1.96 * semeans
keep if pickone
egen order_ = rank(-means), unique
labmask order_, value(country) decode
twoway (dot means order_) (rcap loci hici order_) ///
, legend(off) xlab(1/29, valuelabels ang(v)) ///
ylabel(, format(%6.1f)) ///
ytitle("Self-rated health") ///
xtitle("") ///
note(`"Note: SRH ranges from 0 ("poor") to 4 ("excellent")"', span)
restore
preserve logit srh_bin i.country [pweight = weight] predict lr_index, xb predict se_index, stdp generate p_hat = exp(lr_index)/(1+exp(lr_index)) // Predicted probabilities // (following http://www.stata.com/support/faqs/...) gen lb = lr_index - invnormal(0.975)*se_index gen ub = lr_index + invnormal(0.975)*se_index gen plb = exp(lb)/(1+exp(lb)) gen pub = exp(ub)/(1+exp(ub)) replace p_hat = p_hat * 100 replace plb = plb * 100 replace pub = pub * 100 keep if pickone egen order_ = rank(p_hat), unique labmask order_, value(country) decode twoway (dot p_hat order_) (rcap plb pub order_) /// , legend(off) xlab(1/29, valuelabels ang(v)) /// ylabel(, format(%6.0f)) /// ytitle("% Poor health") xtitle("")
Mar 26, 2013
Random graphs (11): Visualizing multiple group differences
// Prepare data // Formal care use by income quintiles, households with a child input str5 geo inc1 inc3 inc5 AT 10 7 9 BE 17 38 57 BG 0 10 15 CH 9 27 53 CY 16 19 30 CZ 3 3 4 DE 21 22 23 DK 87 72 83 EE 16 22 14 EL 6 11 12 ES 29 30 45 FI 18 27 41 FR 15 60 64 HR 6 8 13 HU 7 14 15 IE 8 12 34 IS 37 44 34 IT 17 26 28 LT 2 16 10 LU 23 34 56 LV 7 24 11 MT 0 16 15 NL 27 55 70 NO 34 57 53 PL 0 2 4 PT 14 44 36 RO 5 5 13 SE 44 56 32 SI 41 39 38 SK 2 5 0 UK 20 50 53 EU-27 17 34 36 end // Encode country variable encode geo, gen(country) // Create country variable sortet by the size of the income gap gen diff = inc5 - inc1 // Income gap egen order = rank(-diff), unique // Create rank variable labmask order, value(country) decode // Assign value // labels of country to variable order based on its values
// Run-of-the-mill dot plot
twoway dot inc1 inc3 inc5 order, vertical ///
legend(label(1 "1{sup:st} income quintile (poorest)") ///
label(2 "3{sup:rd} income quintile") ///
label(3 "5{sup:th} income quintile (richest)") ///
order(3 2 1) ring(0) pos(12)) ///
msymbol(th oh t) ///
xlabel(1/32, valuelabels ang(v)) /// // turn on labels
xtitle("") ///
ytitle("% formal care use of households with" ///
"a child younger than 3 years of age") ///
caption("Note: Countries sorted by the size of the difference */
/* between the 5{sup:th} and 1{sup:st} quintile" ///
"Source: EU-SILC 2010", span) ///
name(incomegap1, replace)
// Without dots
scatter inc1 inc3 inc5 order, ///
legend(label(1 "1{sup:st} income quintile (poorest)") ///
label(2 "3{sup:rd} income quintile") ///
label(3 "5{sup:th} income quintile (richest)") ///
order(3 2 1) ring(0) pos(12)) ///
msymbol(th oh t) ///
xlabel(1/32, valuelabels ang(v)) /// // turn on labels
xtitle("") ///
ytitle("% formal care use of households with" ///
"a child younger than 3 years of age") ///
caption("Note: Countries sorted by the size of the difference /*
*/between the 5{sup:th} and 1{sup:st} quintile" ///
"Source: EU-SILC 2010", span) ///
name(incomegap2, replace)
// With numbers instead of symbols
// Not sure whether this is the most elegant move
reshape long inc, i(geo) j(j)
twoway (dot inc order if j == 1, mlabel(j) mlabpos(0) msymbol(i)) ///
(dot inc order if j == 3, mlabel(j) mlabpos(0) msymbol(i)) ///
(dot inc order if j == 5, mlabel(j) mlabpos(0) msymbol(i)), ///
legend(label(1 "1 1{sup:st} income quintile (poorest)") ///
label(2 "3 3{sup:rd} income quintile") ///
label(3 "5 5{sup:th} income quintile (richest)") ///
order(3 2 1) ring(0) pos(12)) ///
xlabel(1/32, valuelabels ang(v)) /// // turn on labels
xtitle("") ///
ytitle("% formal care use of households with" ///
"a child younger than 3 years of age") ///
caption("Note: Countries sorted by the size of the difference /*
*/ between the 5{sup:th} and 1{sup:st} quintile" ///
"Source: EU-SILC 2010", span) ///
name(incomegap3, replace)
// With ordinal numbers and without dots
label define j 1 "1{sup:st}" 3 "3{sup:rd}" 5 "5{sup:th}"
label value j j
twoway (dot inc order if j == 1, mlabel(j) mlabpos(0) msymbol(i) ndots(0)) ///
(dot inc order if j == 3, mlabel(j) mlabpos(0) msymbol(i) ndots(0)) ///
(dot inc order if j == 5, mlabel(j) mlabpos(0) msymbol(i) ndots(0)), ///
legend(label(1 "1{sup:st} income quintile (poorest)") ///
label(2 "3{sup:rd} income quintile") ///
label(3 "5{sup:th} income quintile (richest)") ///
order(3 2 1) ring(0) pos(12)) ///
xlabel(1/32, valuelabels ang(v)) /// // turn on labels
xtitle("") ///
ytitle("% formal care use of households with" ///
"a child younger than 3 years of age") ///
caption("Note: Countries sorted by the size of the difference /*
*/ between the 5{sup:th} and 1{sup:st} quintile" ///
"Source: EU-SILC 2010", span) ///
name(incomegap4, replace)
// With arrows
reshape wide // Get data back into old format
twoway (pcarrow inc5 order inc1 order) ///
(scatter inc5 order) ///
, legend(label(2 "5{sup:th} income quintile (richest)") ///
label(1 "Difference between the 5{sup:th} /*
*/ and 1{sup:st} income quintile") ///
order(1 2) ring(0) pos(12)) ///
xlabel(1/32, valuelabels ang(v)) /// // turn on labels
xtitle("") ///
ytitle("% formal care use of households with" ///
"a child younger than 3 years of age") ///
caption("Note: Countries sorted by the size of the /*
*/ difference between the 5{sup:th} and 1{sup:st} quintile" ///
"Source: EU-SILC 2010", span) ///
name(incomegap5, replace)
// With a line
twoway (rspike inc5 inc1 order) ///
(scatter inc5 order) ///
(scatter inc1 order, msymbol(oh)) ///
(scatter inc3 order, msymbol(th)) ///
, legend(label(3 "1{sup:st} income quintile (poorest)") ///
label(2 "5{sup:th} income quintile (richest)") ///
label(1 "Difference between the 5{sup:th} /*
*/ and 1{sup:st} income quintile") ///
label(4 "3{sup:rd} income quintile") ///
order(2 4 3) ring(0) pos(12)) ///
xlabel(1/32, valuelabels ang(v)) /// // turn on labels
xtitle("") ///
ytitle("% formal care use of households with" ///
"a child younger than 3 years of age") ///
caption("Note: Countries sorted by the size of the difference /*
*/ between the 5{sup:th} and 1{sup:st} quintile" ///
"Source: EU-SILC 2010", span) ///
name(incomegap6, replace)
Labels:
Eurostat data,
labmask,
Random graphs,
scatter,
twoway dot,
twoway pcarrow,
twoway rspike
Mar 15, 2013
Random graphs (7): Differences in percentages across groups
*findit labutil // For the -labmask- command
*ssc install kountry
clear
version 12
// Download date from Eurostat, lfsa_eppga
// Part-time employment as percentage of the total employment
// From 15 to 64 years
input str60 geo m2011 f2011
EU27 8.1 31.6
Belgium 9.2 43.3
Bulgaria 2.0 2.4
"Czech Republic" 1.8 8.5
Denmark 14.2 37.0
Germany 9.0 45.1
Estonia 5.0 13.5
Ireland 12.5 35.2
Greece 4.2 10.0
Spain 5.9 23.4
France 6.5 29.9
Italy 5.5 29.3
Cyprus 6.1 12.1
Latvia 7.0 10.4
Lithuania 6.6 9.9
Luxembourg 4.3 35.9
Hungary 4.4 8.8
Malta 5.3 25.6
Netherlands 24.3 76.5
Austria 7.8 43.4
Poland 4.7 10.4
Portugal 7.0 13.7
Romania 8.7 10.1
Slovenia 7.1 12.2
Slovakia 2.6 5.6
Finland 9.4 19.0
Sweden 12.3 39.3
"United Kingdom" 11.0 42.2
Iceland 9.9 31.7
Norway 13.7 42.1
Switzerland 12.4 59.4
end
// Country
kountry geo, from(other) stuck
ren _ISO3N_ ctry
kountry ctry, from(iso3n) to(iso2c)
kountryadd "Former Yugoslav Republic of Macedonia, the" to "Macedonia" add
replace _ISO2C_ = "EU-27" if geo == "EU27"
drop ctry
ren _ISO2C_ cntry
// Create non-string version of country variable
encode cntry, gen(country)
// Drop unnecessary cases
drop if cntry == "MK"
drop if cntry == "HR"
drop if cntry == "TR"
// First attempts:
graph bar f2011 m2011, over(cntry, sort(1) desc label(angle(90))) ///
legend(label(2 "Men") label(1 "Women")) ///
xsize(8.25) ysize(4)
// A bar graph is too cluttered
graph dot f2011 m2011, over(cntry, sort(1) desc) ///
legend(label(2 "Men") label(1 "Women")) ///
xsize(8.25) ysize(4)
// Can I have that vertically as well?
twoway dot m2011 f2011 country, vertical ///
legend(label(1 "Men") label(2 "Women") ring(0) pos(1)) ///
xlabel(1/31, valuelabels ang(v)) /// // turn on labels
xtitle("") ///
ytitle("% part-time of total employment in 2011") ///
caption("Source: Eurostat, lfsa_eppga, 2013-03-15", span) ///
xsize(8.25) ysize(4)
// Can I sort countries by size of the gender gap?
// Set up sort order
gen diff = f2011 - m2011 // Gender gap
egen order = rank(-diff), unique // Create rank variable
labmask order, value(country) decode // Assign value
// labels of country to variable order based on its values
// Create graph
twoway dot m2011 f2011 order, vertical ///
legend(label(1 "Men") label(2 "Women") ring(0) pos(1)) ///
xlabel(1/31, valuelabels ang(v)) /// // turn on labels
xtitle("") ///
ytitle("% part-time of total employment in 2011") ///
caption("Source: Eurostat, lfsa_eppga, 2013-03-15", span) ///
xsize(8.25) ysize(4)
Labels:
Eurostat data,
graph dot,
labmask,
labutil,
Random graphs,
twoway dot
Subscribe to:
Posts (Atom)































