You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggsankey中跳过NA节点并聚合结果目标的同类链接?

桑基图结局链接排序优化问题

我有如下数据集(实际数据集包含30+列及数千条id):

df <- data.frame(id = 1:5,
                 admission = c("Severe", "Mild", "Mild", "Moderate", "Severe"),
                 d1 = c(NA, "Moderate", "Mild", "Moderate", "Severe"),
                 d2 = c(NA, "Moderate", NA, "Mild", "Moderate"),
                 d3 = c(NA, "Severe", NA, "Mild", NA),
                 d4 = c(NA, NA, NA, "Mild", NA),
                 outcome = c("Dead", "Dead", "Alive", "Alive", "Dead"))

我希望用ggsankey绘制桑基图展示患者每日病情严重程度的变化,要求当观测值为NA(代表已出现结局)时,节点直接链接到结局,预期效果是让同类病情到结局的链接聚合在一起。

初始尝试代码

df.sankey <- df %>%
    make_long(admission, d1, d2, d3, d4, outcome)
ggplot(df.sankey, aes(x = x,
                     next_x = next_x,
                     node = node,
                     next_node = next_node,
                     fill = factor(node),
                     label = node)) +
    geom_sankey(flow.alpha = 0.5,
                node.color = NA,
                show.legend = TRUE) +
    geom_sankey_text(size = 3, color = "black", fill = NA, hjust = 0, position = position_nudge(x = 0.1))

编辑补充

基于解决方案已实现跳过NA节点,但生成的桑基图因结局目标的链接未排序而显得杂乱,代码如下:

do.call(rbind, apply(df, 1, function(x) {
    x <- na.omit(x[-1])
    data.frame(x = names(x), node = x, 
               next_x = dplyr::lead(names(x)), 
               next_node = dplyr::lead(x), row.names = NULL)
})) %>%
    ggplot(df.sankey, aes(x = x,
                          next_x = next_x,
                          node = node,
                          next_node = next_node,
                          fill = factor(node),
                          label = node)) +
    geom_sankey(flow.alpha = 0.5,
                node.color = NA,
                show.legend = TRUE) +
    geom_sankey_text(size = 3, color = "black", fill = NA, hjust = 0, position = position_nudge(x = 0.1))

请问是否可以对结局目标的链接进行排序,将所有Severe值的链接聚合在一起?感谢您的帮助。


内容的提问来源于stack exchange,提问作者amedicalenthusiast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:55:34