当使用ggsurvplot()
进行绘图时,希望通过分类变量为生存曲线着色,该分类变量是用于定义曲线(分层)的分类变量的超集。我已阅读所有文档并搜索答案但未成功。下面提供了可重现的代码,尽管实际的ggsurvplot()
函数调用是伪代码。
library(survival)
library(survminer)
veteran <- veteran
veteran$group <- with(veteran,
ifelse(
celltype == "squamous" | celltype == "smallcell",
"group1", "group2"
)
)
# code used to generate the accompanying plot
surv <- survfit(Surv(time, status) ~ celltype, data = veteran)
ggsurvplot(fit = surv, data = veteran)
我希望曲线的形状和含义保持在上面的生存图中,但是它的颜色为“#squ;”#34;和&#34; smallcell&#34;相同(并表示&#34; group1&#34;)和其他两条曲线具有&#34; group2&#34;颜色。图例应包含两个条目:&#34; group1&#34;和&#34; group2&#34;。
下面是一个示例代码,可以更好地解释我正在尝试做什么(不起作用)
# pseudo-code, version1: without the grouping data in the survfit object
surv <- survfit(Surv(time, status) ~ celltype, data = veteran)
ggsurvplot(fit = surv, color = veteran$group,
legend.labs = levels(factor(veteran$group)), data = veteran)
# pseudo-code, version2: with the grouping data in the survfit
surv <- survfit(Surv(time, status) ~ celltype + group, data = veteran)
ggsurvplot(fit = surv, color = group,
legend.labs = levels(factor(veteran$group)), data = veteran)
编辑:已建议使用palette
函数,但以下代码生成并出现错误
ggsurvplot(fit = surv, palette = c("red", "red", "blue", "blue"), data = veteran)
#Error in names(scurve_cols) <- legend.labs :
#'names' attribute [4] must be the same length as the vector [2]
但是,指定四种不同的颜色有效。
ggsurvplot(fit = surv, palette = c("red", "red1", "blue", "blue1"), data = veteran)
答案 0 :(得分:1)
为了完整性而回答这个问题。用户Henrik在评论中提供的解决方案。可能只适用于最新版本的幸运者[0.4.0]。
library(survival)
library(survminer)
veteran <- veteran
#coding an external 'superset' variable is unnecessary
surv <- survfit(Surv(time, status) ~ celltype, data = veteran)
ggsurvplot(fit = surv, palette = c("red", "red", "blue", "blue"), data = veteran)