Search code examples
rggplot2survival-analysis

Add scatter points on top of ggsurvplot


After calling ggsurvplot(...) I want to superimpose some points from another data frame df containing two columns time and survival. I'm looking for tips on accomplishing this.

Edit: some code as an example

require("survival")
require("survminer")
fit<- survfit(Surv(time, status) ~ sex, data = lung)

# Basic survival curves
ggsurvplot(fit, data = lung)

# Example points
x <- fit$time
y <- fit$n.risk

How would I superimpose points(x, y) on ggsurvplot plot.


Solution

  • The ggplot-type object is part of the object returned by ggsurvplot() and can be addressed as $plot:

    ggplot1 <- ggsurvplot(fit, data = lung)$plot
    

    You can work with it as with a usual ggplot object and add other layers. For your specific example, however, it is not clear how you want to define Y coordinate of your points: fit$n.risk is a number between 1 and 138 while your plot is in 0..1 range. Here is one option:

    ggplot1 <- ggsurvplot(fit, data = lung)$plot
    df1 <- data.frame(time=fit$time, nRisk=fit$n.risk, nRiskRel=fit$n.risk/max(fit$n.risk))  
    ggplot1 + geom_point(aes(x=time, y=nRiskRel), data = df1, alpha=0.5, size=3)
    

    example plot

    You may want to add colors etc.