// Combining different graphs with the graph combine command // Author: Chuck Huber, Stata Corps. //Shared with permission for UCSF Biostat 212 students, Summer 2018 // ========================================================= webuse nhanes2, clear rename bpsystol sbp replace sex = 0 if sex==2 // STEP 1: Fit the regression model regress sbp c.age##i.sex // STEP 2: Estimate the linear prediction of sbp using margins margins sex, at(age=(20(10)80)) // STEP 3: Use marginsplot with the addplot() option to create the regression lines and scatterplot #delimit ; marginsplot, recast(line) noci plot1opts(lcolor(cranberry) lwidth(thick)) plot2opts(lcolor(navy) lwidth(thick)) title("") addplot( (scatter sbp age if sex==1, mcolor(navy) msize(vsmall) msymbol(circle)) (scatter sbp age if sex==0, mcolor(cranberry) msize(vsmall) msymbol(circle)) , legend(off) xlabel(20(10)80, grid gmax) ylabel(50(50)275) yscale(off) xscale(off range(20 80)) xline(80, lcolor(black) lwidth(medium)) ) text(272 20.2 "Females", color(cranberry) size(vlarge) justification(left) placement(right)) text(257 20.2 "Males", color(navy) size(vlarge) justification(left) placement(right)) name(sbpage, replace) ; #delimit cr // STEP 4: Create, resize and store a histogram for age #delimit ; twoway histogram age, fraction fcolor(gs12) lcolor(black) lwidth(vthin) xtitle(, size(medium)) xlabel(20(10)80,grid gmax) ytitle("") ylabel(, nogrid labsize(small) angle(horizontal)) yscale(off reverse) fysize(20) name(hage, replace) ; #delimit cr // STEP 5: Create, resize and store a histogram for sbp #delimit ; twoway histogram sbp, fraction fcolor(gs12) lcolor(black) lwidth(vthin) ytitle(, size(medium) orientation(vertical)) ylabel(50(50)275, grid gmax labsize(small) angle(horizontal)) xlabel(none, nogrid) xtitle("") xscale(off reverse) horizontal fxsize(20) name(hsbp, replace) ; #delimit cr // STEP 6: Create, resize and store a bar graph for sex #delimit ; graph bar, over(sex) asyvars stack bar(1, fcolor(cranberry)) bar(2, fcolor(navy)) yscale(alt) ytitle(Proportion of males and females, size(medium) orientation(vertical)) ylabel(, nogrid labsize(small) angle(horizontal)) legend(off) fxsize(15) name(bsex, replace) ; #delimit cr // STEP 7: Use -graph combine- to assemble the final graph #delimit ; graph combine hsbp sbpage bsex hage, rows(2) cols(3) hole(4 6) imargin(0 0 0 0 0 0) graphregion(margin(l=0 r=0)) title("Systolic Blood Pressure by Age and Sex") ; #delimit cr