R: plotting graphs (ggplot vs autoplot)

谁说胖子不能爱 提交于 2021-01-05 08:56:05

问题


I am following a R tutorial over here https://rviews.rstudio.com/2017/09/25/survival-analysis-with-r/

The computer I use for work does not have internet access nor a USB port - it only has R with some preinstalled libraries. The tutorial requires "survival", "ggplot2", "ranger", "dplyr" and "ggfortify". The computer I use for work has all of these libraries EXCEPT ggfortfiy. Apparently, a function called "autoplot" is required from the ggfortify library to make some of the plots in this tutorial.

When I try to run the code from the 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)

I get the following error: Error: Objects of type survfit not supported by autoplot.

Does anyone know how to fix this? Is it possible to make similar plots without the ggfortify library? Can it just be made with ggplot2?

On my personal computer, I am able to make this plot once I install the ggfortify library.

(note: I also do not have the "survminer" library)

Thanks


回答1:


Yes, this is possible, because the autoplot function uses ggplot2 under the hood:

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)


来源:https://stackoverflow.com/questions/65033260/r-plotting-graphs-ggplot-vs-autoplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!