【问题标题】:R: plotting graphs (ggplot vs autoplot)R:绘图(ggplot vs autoplot)
【发布时间】:2020-11-27 07:05:06
【问题描述】:

我在这里学习 R 教程https://rviews.rstudio.com/2017/09/25/survival-analysis-with-r/

我用于工作的计算机没有互联网访问权限,也没有 USB 端口 - 它只有 R 和一些预装的库。本教程需要“survival”、“ggplot2”、“ranger”、“dplyr”和“ggfortify”。我用于工作的计算机具有所有这些库,除了 ggfortfiy。显然,ggfortify 库中需要一个名为“autoplot”的函数来制作本教程中的一些绘图。

当我尝试运行教程中的代码时:

#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)

我收到以下错误:Error: Objects of type survfit not supported by autoplot.

有谁知道如何解决这个问题?如果没有 ggfortify 库,是否可以制作类似的图?可以只用ggplot2制作吗?

在我的个人电脑上,一旦我安装了 ggfortify 库,我就可以制作这个绘图了。

(注意:我也没有“survminer”库)

谢谢

【问题讨论】:

    标签: r ggplot2 plot graph data-visualization


    【解决方案1】:

    是的,这是可能的,因为autoplot 函数在底层使用了ggplot2

    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)
    

    【讨论】:

    • 这太完美了!谢谢!你能解释一下你是怎么得出这个答案的吗?
    • 我尝试为教程的下一部分调整您的代码。在下一部分中,生成了一个图表,但它看起来与教程不同。 km_trt_fit % ggplot(aes (x = time, group = factor(veteran$trt), color = factor(veteran$trt), fill = factor(veteran$trt))) + geom_line(aes(y = surv)) + geom_ribbon(aes(ymin = min, ymax = max), alpha = 0.3)
    • (这里有一个更简洁的版本:shrib.com/#Jordan-zj6Moa
    • (这里有后续帖子:stackoverflow.com/questions/65042472/…
    猜你喜欢
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 2022-12-25
    • 2014-06-19
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 2014-05-16
    相关资源
    最近更新 更多