title: Plotting predicted survival curves for continuous covariates in ggplot
body: <p>How can I plot survival curves for representative values of a continuous covariate in a cox proportional hazards model? Specifically, I would like to do this in ggplot using a "survfit.cox" "survfit" object. </p>
  
  <p>This may seem like a question that has already been answered, but I have searched through everything in SO with the terms 'survfit' and 'newdata' (plus many other search terms). This is the thread that comes closest to answering my question so far: <a href="https://stackoverflow.com/questions/32076310/plot-kaplan-meier-for-cox-regression/32104623#32104623">Plot Kaplan-Meier for Cox regression</a></p>
  
  <p>In keeping with the reproducible example offered in one of the answers to that post:</p>
  
  <pre><code>url &lt;- "http://socserv.mcmaster.ca/jfox/Books/Companion/data/Rossi.txt"
  df &lt;- read.table(url, header = TRUE)
  
  library(dplyr)
  library(ggplot2)
  library(survival)
  library(magrittr)
  library(broom)
  
  # Identifying the 25th and 75th percentiles for prio (continuous covariate)
  
  summary(df$prio)
  
  # Cox proportional hazards model with other covariates
  # 'prio' is our explanatory variable of interest
  
  m1 &lt;- coxph(Surv(week, arrest) ~ 
                         fin + age + race + prio,
                       data = df)
  
  # Creating new df to get survival predictions
  # Want separate curves for the the different 'fin' and 'race'
  # groups as well as the 25th and 75th percentile of prio
  
  newdf &lt;- df %$%
    expand.grid(fin = levels(fin), 
                      age = 30, 
                      race = levels(race), 
                      prio = c(1,4))
  
  # Obtain the fitted survival curve, then tidy 
  # into a dataframe that can be used in ggplot
  
  survcurv &lt;- survfit(m1, newdata = newdf) %&gt;%
    tidy()
  </code></pre>
  
  <p>The problem is, that once I have this dataframe called <code>survcurv</code>, I cannot tell which of the 'estimate' variables belongs to which pattern because none of the original variables are retained. For example, which of the 'estimate' variables represents the fitted curve for 30 year old, race = 'other', prio = '4', fin = 'no'?</p>
  
  <p>In all other examples i've seen, usually one puts the survfit object into a generic <code>plot()</code> function and does not add a legend. I want to use ggplot and add a legend for each of the predicted curves. </p>
  
  <p>In my own dataset, the model is a lot more complex and there are a lot more curves than I show here, so as you can imagine seeing 40 different 'estimate.1'..'estimate.40' variables makes it hard to understand what is what.</p>