UCLA Academic Technology Services HomeServicesClassesContactJobs
Search

Stata Code Fragment: 
A code fragment for displaying hazard ratio of different baseline characteristics by a dichotomous variable

The scheme used for this plot can be downloaded by "findit lean scheme" from within Stata. This example here has a couple of steps. First step is to run all the models and store the parameter estimates and standard errors in a temporary file. Then it opens the temporary file as a data set and computes the hazard ratio, the confidence interval and its p-value. The last step is to plot them in a compact fashion. The command "labmask" is part of the labutil module written by Nicholas J. Cox and can be downloaded via "findit labutil".

use http://www.stata-press.com/data/cgg/hip3, clear
 
/*creating variable names for the output file*/
capture file close a
file open a using "hr.txt", write replace
file write a "raw_coeff" _tab "stderr" _tab "variable"  _tab "case" _n

/*running separate model on each binary variable and store the estimates*/

foreach var of varlist male calcium {
  tempvar intcat
  gen `intcat' =`var'*protect
  stcox protect `var' `intcat'
  lincom  `var' /*case 0*/
  file write a (`r(estimate)') _tab (`r(se)') _tab ("`var'") _tab (0) _n
  lincom  `var' + `intcat' /*case 1*/
  file write a (`r(estimate)') _tab (`r(se)') _tab ("`var'")  _tab (1) _n 

}

file close a

insheet using hr.txt, clear

gen hzratio=exp(raw_coeff)
gen lower=exp(raw_coeff - 1.96*stderr)
gen upper=exp(raw_coeff + 1.96*stderr)

gen p_value = 2*(1-normal(abs(raw_coeff/stderr)))
gen pstring = string(p_value, "%4.3f")

egen group=group(variable case), label

gen group2 = group

labmask group2, values(pstring)

twoway  (scatter group hzratio, msymbol(square)) (rspike lower upper group2, hor yaxis(2)), ///
        legend(off) xline(1, lstyle(refline))  xlabel(0(1) 2) xscale(range(-1 2))  ///
        xtitle(hazard ratio) xsize(4) ylabel(, valuelabel axis(1) tlength(0)) yscale(lstyle(none) axis(1)) ///
        ysize(5) plotregion(style(none)) ylabel(, valuelabel axis(2) tlength(0)) yscale(lstyle(none) axis(2)) ///
        ytitle("", axis(1)) ytitle("", axis(2))  scheme(lean1) 


How to cite this page

Report an error on this page

UCLA Researchers are invited to our Statistical Consulting Services
We recommend others to our list of Other Resources for Statistical Computing Help
These pages are Copyrighted (c) by UCLA Academic Technology Services


The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California