如何在R中绘制格子/刻面样式的累积发生率图?

时间:2017-04-12 13:18:28

标签: r plot

我想创建一个格子/刻面图,以查看我的数据中几个组的累积发生率。

所以我开始了
library(rms)
library(dplyr)

data(colon)
fit1 <- npsurv(Surv(time, status) ~ 1, data = colon %>% filter(rx=="Obs"))
survplot(fit1, fun = function(x) 1-x)
fit2 <- npsurv(Surv(time, status) ~ 1, data = colon %>% filter(rx=="Lev"))
survplot(fit2, fun = function(x) 1-x)
fit3 <- npsurv(Surv(time, status) ~ 1, data = colon %>% filter(rx=="Lev+5FU"))
survplot(fit3, fun = function(x) 1-x)

然后我坚持将三个情节放在一起,并在每个情节的顶部显示组的名称。我不喜欢mfrowmfcol解决方案。有人可以解释如何使用latticeggplot2来执行此操作吗?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

采用tidyverse方法 - 使用purrr::mappurrr:map_dfrx的每个级别拟合模型。 1 - x部分留给读者作为练习。唯一的魔法&#39;部分正在使用mgetnpsurv的类似列表的结果进行子集化,以仅获取绘图所需的列。

library(rms)
library(tidyverse)
data(colon)

colon %>%
  split(.$rx) %>%
  map(~ npsurv(Surv(time, status) ~ 1, data = .)) %>%
  map_df(~ mget(c("surv", "upper", "lower", "time"), 
                as.environment(.)) %>%
           data.frame, 
         .id = "rx") %>%
  ggplot(aes(time)) + 
  geom_ribbon(aes(ymin = lower, ymax = upper), fill = "gray80") +
  geom_line(aes(y = surv)) +
  facet_wrap(~ rx)

Survival as a trellis plot

答案 1 :(得分:0)

我自己想通了。这是我的解决方案

require(rms)
require(dplyr)
data(colon)
dat <- list()
for (i in 1:length(unique(colon$rx))) {
    j = sort(unique(colon$rx))[i]
    fit <- npsurv(Surv(time, status) ~ sex, data = colon%>%filter(rx == j))
    dat[[i]] <- data.frame(Time = fit$time,
                            Probability = 1 - fit$surv,
                            Group = c(rep("Male", fit$strata[1]), rep("Female", fit$strata[2])),
                            Center = j)
}
data_all <- do.call(rbind, dat)
data_all$Group <- factor(data_all$Group, levels = c("Male", "Female"))

require(lattice)
p <- xyplot(Probability ~ Time| Center, group = Group, data = data_all, 
            grid = T, type = "l", 
            auto.key = list("top", lines = T, points = F),
            par.settings = list(lwd = 2))
p