Search code examples
rggplot2survival-analysissmoothing

R smooth survival curve force start and end


I would like to smooth a survival curve so it has no 'steps'. With the following data I am trying this:

library(ggplot2)
df1<-data.frame(y=c(1,0.99,0.97,0.95,0.94,0.94,0.82,0.72,0.58,0.34,0.20,0.12,0.11,0), 
time=c(3,4,7,8,10,11,13,14,15,17,20,22,23,24))
ggplot(df1, aes(time,y)) + geom_point() +
  geom_smooth(method = "gam", formula = y ~ poly(x, 2),se=F) 

enter image description here

But the smoothed line has start point higher than one as well as end point lower than 0 ( Which for a survival plot is impossible). How could fit a line that:

  1. Line start at y,x values= 1,0
  2. ends at y,x values=0,24
  3. always monotonic decreasing function

Solution

  • Based on IRTFM comment I was able to find the answer, here is the code:

    library(cobs)
    library(ggplot2)
    df1<-data.frame(y=c(1,0.99,0.97,0.95,0.94,0.94,0.82,0.72,0.58,0.34,0.20,0.12,0.11,0), 
                time=c(3,4,7,8,10,11,13,14,15,17,20,22,23,24))
    
    con2 <- rbind(c( 1,min(df1$time),1), 
              c(-1,max(df1$time),0)) 
    
    Sb1 <- cobs(df1$time,df1$y, constraint="decrease", nknots=4,pointwise= con2,
            degree = 2)
    
    summary(Sb1)
    plot(Sb1, main='Survival Curve')
    

    enter image description here

    Thanks