r - 使用包“cmprsk”在 R 中自定义竞争风险图
问题描述
我正在尝试使用 R 和 package 自定义竞争风险的情节cmprsk
。具体来说,我想覆盖使用竞争事件颜色和使用不同组线型的默认设置。
这是我的可重现示例:
library(ggplot2)
library(cmprsk)
library(survminer)
# some simulated data to get started
comp.risk.data <- data.frame("tfs.days" = rweibull(n = 100, shape = 1, scale = 1)*100,
"status.tfs" = c(sample(c(0,1,1,1,1,2), size=50, replace=T)),
"Typing" = sample(c("A","B","C","D"), size=50, replace=T))
# fitting a competing risks model
CR <- cuminc(ftime = comp.risk.data$tfs.days,
fstatus = comp.risk.data$status.tfs,
cencode = 0,
group = comp.risk.data$Typing)
# the default plot makes it impossible to identify the groups
ggcompetingrisks(fit = CR, multiple_panels = F, xlab = "Days", ylab = "Cumulative incidence of event",title = "Competing Risks Analysis")+
scale_color_manual(name="", values=c("blue","red"), labels=c("Tumor", "Death without tumor"))
使用ggplot_build()
我设法更改了有关线型和颜色的默认值,但我找不到添加图例的方法。
p2 <- ggcompetingrisks(fit = CR, multiple_panels = FALSE, xlab = "Days", ylab = "Cumulative incidence of event",title = "Death by TCR", ylim = c(0, 1)) +
scale_color_manual(name="", values=c("blue","red"), labels=c("Tumor", "Death without tumor"))
q <- ggplot_build(p2)
q$data[[1]]$colour2 <- ifelse(q$data[[1]]$linetype=="solid","blue", ifelse(q$data[[1]]$linetype==22,"red", ifelse(q$data[[1]]$linetype==42,"green", ifelse(q$data[[1]]$linetype==44,"black", NA))))
q$data[[1]]$linetype <- ifelse(q$data[[1]]$colour=="blue","solid", ifelse(q$data[[1]]$colour=="red","dashed", NA))
q$data[[1]]$colour <- q$data[[1]]$colour2
q$plot <- q$plot + ggtitle("Competing Risks Analysis") + guides(col = guide_legend()) + theme(legend.position = "right")
p2 <- ggplot_gtable(q)
plot(p2)
有谁知道如何将图例添加到由 操纵的情节ggplot_build()
?或者另一种绘制竞争风险的方法,例如颜色指示组和线型指示事件?
解决方案
你不需要沿着这ggplot_build
条路走。该函数ggcompetingrisks
返回一个 ggplot 对象,该对象本身包含美学映射。您可以使用以下命令覆盖这些aes
:
p <- ggcompetingrisks(fit = CR,
multiple_panels = F,
xlab = "Days",
ylab = "Cumulative incidence of event",
title = "Competing Risks Analysis")
p$mapping <- aes(x = time, y = est, colour = group, linetype = event)
现在我们已经反转了线型和颜色美学映射,我们只需要交换图例标签就可以了:
p + labs(linetype = "event", colour = "group")
p
请注意,您还可以像任何其他 ggplot 对象一样添加色阶、主题、坐标变换。
推荐阅读
- php - PHP致命错误:require():需要打开失败
- java - 如何在 Maven 项目中包含已编译的二进制文件?
- cloud-foundry - 如何在 CloudFoundry 上运行 Selenium-Grid?
- azure - 通过 arm 模板创建 HDInsight 群集时出错
- orgchart - GetOrgChart - 渲染、更新、删除等
- typescript - Typescript 在函数类型定义中的传播
- angular - D3.js 和 Angular 'this' 元素冲突
- sql - 数组重叠运算符的 GIN 索引具有 O(N^2) 复杂度?
- javascript - npm 模块依赖图不相似
- javascript - 带有 mkdocs 的本地 mathjax