R: trazado de gráficos (ggplot vs autoplot)

Nov 27 2020

Estoy siguiendo un tutorial de R aquí https://rviews.rstudio.com/2017/09/25/survival-analysis-with-r/

La computadora que uso para el trabajo no tiene acceso a Internet ni puerto USB, solo tiene R con algunas bibliotecas preinstaladas. El tutorial requiere "survival", "ggplot2", "ranger", "dplyr" y "ggfortify". La computadora que uso para el trabajo tiene todas estas bibliotecas EXCEPTO ggfortfiy. Aparentemente, se requiere una función llamada "autoplot" de la biblioteca ggfortify para hacer algunos de los gráficos de este tutorial.

Cuando intento ejecutar el código del tutorial:

#load libraries
library(survival)
library(ranger)
library(ggplot2)
library(dplyr)

#load data
data(veteran)
head(veteran)

# Kaplan Meier Survival Curve
km <- with(veteran, Surv(time, status))
km_fit <- survfit(Surv(time, status) ~ 1, data=veteran)

#plot(km_fit, xlab="Days", main = 'Kaplan Meyer Plot') #base graphics is always ready


#here is where the error is 
autoplot(km_fit)

Obtuve el siguiente error: Error: Objects of type survfit not supported by autoplot.

¿Alguien sabe cómo arreglar esto? ¿Es posible hacer gráficos similares sin la biblioteca ggfortify? ¿Se puede hacer con ggplot2?

En mi computadora personal, puedo hacer este gráfico una vez que instalo la biblioteca ggfortify.

(nota: tampoco tengo la biblioteca "survminer")

Gracias

Respuestas

Till Nov 27 2020 at 16:28

Sí, esto es posible, porque la autoplotfunción utiliza ggplot2bajo el capó:

tibble(time = km_fit$time, surv = km_fit$surv, 
       min = km_fit$lower, max = km_fit$upper) %>% 
  ggplot(aes(x = time)) +
  geom_line(aes(y = surv)) +
  geom_ribbon(aes(ymin = min, ymax = max), alpha = 0.3)