R Shiny中ggcuminc单风险组时图例消失的解决方法
解决R Shiny中ggcuminc单组时图例消失的问题
当风险组仅包含一个取值时,ggplot会自动隐藏图例——默认逻辑认为单个类别无需图例标注。要强制保留图例,可通过以下两种方式修改代码:
方法一:用guides()强制启用图例
在绘图代码末尾添加guides()函数,明确指定显示颜色和线型图例:
rrfit <- tidycmprsk::cuminc(Surv(EFS.Years, EFS.eventID) ~ Risk, data = combined_data) %>% ggcuminc(outcome = 'Relapse', theme = theme_minimal(), size = 1, linetype_aes = TRUE) + labs(x = "Years", y = "Cumulative Incidence") + coord_cartesian(ylim = c(0,1)) + scale_color_manual(values = palette_vector) + scale_linetype_manual(values = linetype_vector) + scale_x_continuous(limits=c(0,10), breaks=seq(from=0, to=10, by=1)) + add_legend_title(title = paste(legend_vector1, "n:", sample_vector, collapse = "\n")) + # 强制显示颜色和线型图例 guides(color = guide_legend(), linetype = guide_legend())
方法二:结合theme()指定图例位置并强制显示
如果需要自定义图例位置(如右侧、底部),可在theme()中设置legend.position,同时配合guides()确保图例不被隐藏:
rrfit <- tidycmprsk::cuminc(Surv(EFS.Years, EFS.eventID) ~ Risk, data = combined_data) %>% ggcuminc(outcome = 'Relapse', theme = theme_minimal(), size = 1, linetype_aes = TRUE) + labs(x = "Years", y = "Cumulative Incidence") + coord_cartesian(ylim = c(0,1)) + scale_color_manual(values = palette_vector) + scale_linetype_manual(values = linetype_vector) + scale_x_continuous(limits=c(0,10), breaks=seq(from=0, to=10, by=1)) + add_legend_title(title = paste(legend_vector1, "n:", sample_vector, collapse = "\n")) + # 指定图例位置为右侧 theme(legend.position = "right") + # 强制显示图例 guides(color = guide_legend(), linetype = guide_legend())
注意:需确保单组场景下palette_vector和linetype_vector为长度1的向量,保证颜色、线型设置正常生效。
内容的提问来源于stack exchange,提问作者Jack Pep
相关产品推荐
相关产品推荐

