rggplot2ggfortify

Error adding new curve to survival curve in ggplot?


I want to add a new line and confidence band to a survival analysis plot (Kaplan-Meier curve) created using autoplot from the ggfortify package.

However, I receive an error when using geom_ribbon but not when using geom_line. The minimal example below illustrates the issue.

# Load packages and data
library(survival)
library(ggfortify)
data(aml, package = "survival")

# Fit the Kaplan-Meier curve
fit <- survfit(Surv(time, status) ~ x, data=aml)

# Create an additional dataset to plot on top of the Kaplan-Meier curve
df <- data.frame(x = seq(1, 150, length.out=10),
                 y = seq(0, 1, length.out=10),
                 ymin = seq(0, 1, length.out=10) - 0.1,
                 ymax = seq(0, 1, length.out=10) + 0.1)

This works

autoplot(fit, conf.int = FALSE, censor = FALSE) +
  geom_line(data = df, mapping = aes(x=x, y=y)) +
  geom_line(data = df, mapping = aes(x=x, y=ymin)) +
  geom_line(data = df, mapping = aes(x=x, y=ymax))

enter image description here

This does not work

autoplot(fit, conf.int = FALSE, censor = FALSE) +
  geom_ribbon(data = df, mapping = aes(x=x, ymin=ymin, ymax=ymax))
Error in FUN(X[[i]], ...) : object 'surv' not found

Solution

  • If you specify inherit.aes = FALSE in geom_ribbon() you avoid that specific error, i.e.

    library(survival)
    #install.packages("ggfortify")
    library(ggfortify)
    #> Warning: package 'ggfortify' was built under R version 4.1.2
    #> Loading required package: ggplot2
    data(aml, package = "survival")
    #> Warning in data(aml, package = "survival"): data set 'aml' not found
    
    # Fit the Kaplan-Meier curve
    fit <- survfit(Surv(time, status) ~ x, data=aml)
    
    # Create an additional dataset to plot on top of the Kaplan-Meier curve
    df <- data.frame(x = seq(1, 150, length.out=10),
                     y = seq(0, 1, length.out=10),
                     ymin = seq(0, 1, length.out=10) - 0.1,
                     ymax = seq(0, 1, length.out=10) + 0.1)
    
    autoplot(fit, conf.int = FALSE, censor = FALSE) +
      geom_line(data = df, mapping = aes(x=x, y=y)) +
      geom_line(data = df, mapping = aes(x=x, y=ymin)) +
      geom_line(data = df, mapping = aes(x=x, y=ymax))
    

    autoplot(fit, conf.int = FALSE, censor = FALSE) +
      geom_ribbon(data = df, mapping = aes(x=x, ymin=ymin, ymax=ymax),
                  inherit.aes = FALSE)
    

    Created on 2022-02-21 by the reprex package (v2.0.1)

    Does that solve your problem?