*! version 3.0.1  JMGarrett 17Nov99
/* Plot predicted survival curves from the Cox model by categories of X    */
/* Form: stcoxplt, xvar(xvar) options                                      */
/* Must have stset data before using this command                          */
/* Options: model, adjust, nolog, noshow, symbol, connect, titles, labels  */

program define stcoxplt
  version 6.0
  st_is 2 analysis
  #delimit ;
    syntax [if] [in], Xvar(varname) [Range(real 0)
      L1title(string) L2title(string) Model ADJust(string) YLAbel(string)
      NOSHow NOLOg * ] ;
  #delimit cr
  marksample touse
  markout `touse' `xvar'
  preserve
  local t: char _dta[st_bt]
  local d: char _dta[st_bd]
  local t0: char _dta[st_bt0]
  local id: char _dta[st_id]
  quietly keep if `touse'
  local xlbl : variable label `xvar'
  if "`xlbl'"=="" {local xlbl="`xvar'"}
  local timelbl : variable label `t'

* If there are covariates, drop missing, center or use specified values
  tokenize "`adjust'"
  local numcov 0
  local i 1
  while "`1'"~="" {
    local equal=index("`1'","=")
    if `equal'==0  {
       local cov`i'="`1'"
       local mcov`i'="mean"
       }
    if `equal'~=0  {
       local cov`i'=substr("`1'",1,`equal'-1)
       local mcov`i'=substr("`1'",`equal'+1,length("`1'"))
       }
    quietly drop if `cov`i''==.
    local covlist `covlist' `cov`i''
    local i=`i'+1
    macro shift
    local numcov=`i'-1
    }
  local i 1
  while `i'<=`numcov' {
    if "`mcov`i''"=="mean" {
      quietly sum `cov`i''
      quietly replace `cov`i''=`cov`i''-_result(3)
      }
    if "`mcov`i''"~="mean" {
      quietly replace `cov`i''=`cov`i''-`mcov`i''
      }
    local i=`i'+1
    }

* Create dummy variables from X and create variable lists
  keep `xvar' `d' `t' `t0' `id' `covlist'
  quietly tab `xvar', gen(x)
  local numcat=_result(2)
  local i 1
  while `i'<=`numcat' {
    if `i'>1 {local xlist `xlist' x`i'}
    local varlbl`i' : variable label x`i'
    local i=`i'+1
    }

* Run Cox model and create survival probabilies
  quietly streset
  if "`model'"=="model" {
     if "`nolog'"=="" {stcox `xlist' `covlist', bases(surv1)}
     if "`nolog'"~="" {stcox `xlist' `covlist', bases(surv1) nolog}
     more
     }
  if "`model'"==""  {
    if "`noshow'"=="" {st_show}
    quietly stcox `xlist' `covlist', bases(surv1)
    }
  local i=1
  while `i'<=`numcat'  {
    if `i'>1 {quietly gen surv`i'=surv1^exp(_b[x`i'])}
    format surv`i' %3.2f
    label var surv`i' "`varlbl`i''"
    local i=`i'+1
    }
  format surv1 %3.2f
  keep `t' surv*
  sort `t'
  if `range'>0 {
     quietly keep if mod(`t',`range')==0 | _n==1 | _n==_N
     }
  label var `t' "`timelbl'"

* Plot results
  if "`l1title'"=="" {local l1title "Cox Model Survival Probabilities"}
  if "`l2title'"=="" {local l2title "By Categories of `xlbl'"}
  if "`ylabel'"=="" {local ylabel "ylabel(0,.25,.50,.75,1)"}
  else local ylabel "ylabel(`ylabel')"
  graph surv* `t', `ylabel' l1("`l1title'") l2("`l2title'") `options'
end