With par(new=TRUE)
you can draw a second plot in the same figure as the first.
Normally I would recommend using lines()
for adding curves to a plot, since par(new=TRUE)
performs the filosophically different task of overlaying plots. When using functions in a way they are not intended to be used you risk commiting misstakes, e.g. I nearly forgot the vital xlim
argument. However, it is not trivial to extract the curves from the survfit
objects, so I figured it was the lesser of two evils.
# Fake data for the plots
pump <- data.frame(TIME=rweibull(40, 2, 20),
CENSUS=runif(40) < .3,
DEVICE=rep(0:1, c(20,20)))
# load package
library("survival")
# Fit models
mfit.overall <-survfit(Surv(TIME, CENSUS==0) ~ 1, data=pump)
mfit.htx <- survfit(Surv(TIME, CENSUS==0) ~ 1, data=pump, subset=DEVICE==1)
# Plot
plot(mfit.overall, col=1, xlim=range(pump$TIME), fun=function(x) 1-x)
# `xlim` makes sure the x-axis is the same in both plots
# `fun` flips the curve to start at 0 and increase
par(new=TRUE)
plot(mfit.htx, col=2, xlim=range(pump$TIME), fun=function(x) 1-x,
ann=FALSE, axes=FALSE, bty="n") # This hides the annotations of the 2nd plot
legend("topright", c("All", "HTX"), col=1:2, lwd=1)