I have a couple cuminc
objects from the cmprsk
package, which I want to appear on the same plot. However, plot.cuminc
apparently does not work with lines. I tried to plot the objects together like so.
library(cmprsk)
data1<-data.frame(status=c(rep(0,20),rep(1,20),rep(2,20)),time=runif(n=60, min=1, max=20))
data2<-data.frame(status=c(rep(0,15),rep(1,35),rep(2,10)),time=runif(n=60, min=1, max=20))
a<-cuminc(data1$time,data1$status)
b<-cuminc(data2$time,data2$status)
plot(a[1])
lines(b[1])
But I got an error that says:
Error in xy.coords(x, y) :
'x' is a list, but does not have components 'x' and 'y'
I can also do ggcompetingrisks(a)
and ggcompetingrisks(b)
, but I couldn't get two curves on the same plot this way - I can only plot these on one larger plot where they are still separate (for example with cowplot
).
How can I plot the two objects together?
edit: I was able to use tidycmprsk::cuminc, then apply tidy() to get the estimates in a data frame, and plot from there. However it would still be helpful to do it without having to use this package and the extra processing.
data1<-data.frame(status=as.factor(c(rep('censor',20),rep('event',20),rep('death',20))),time=runif(n=60, min=1, max=20))
data2<-data.frame(status=as.factor(c(rep('censor',15),rep('event',35),rep('death',10))),time=runif(n=60, min=1, max=20))
obj1<-tidycmprsk::cuminc(Surv(time, status) ~ 1, data1)
obj2<-tidycmprsk::cuminc(Surv(time, status) ~ 1, data2)
fit1<-filter(tidy(obj1),outcome=='event')
fit2<-filter(tidy(obj2),outcome=='event')
plot(fit1$time,fit1$estimate,type='l')
lines(fit2$time,fit2$estimate,type='l',lty=2)
There is no lines.cuminc()
because plot.cuminc()
handles multiple lines by default - as it shows the cumulative incidence of each hazard.
You have a slightly unusual situation in that you want to plot lines from different models. But as the plot.cuminc()
docs state, the first argument is:
a list, with each component representing one curve in the plot... Although written for cumulative incidence curves, can in principle be used for any set of lines.
Under the hood it calls plot()
for the first curve and then lines()
for each additional one. So we can simply construct such a list from each of your model objects and provide it to plot.cuminc()
:
ab <- list(a = a[[1]], b = b[[1]])
plot.cuminc(ab, color = c("red", "blue"), lwd = 2)