如何使用ggsankey自定义桑基图第二层节点的显示顺序?
调整ggsankey桑基图第二层节点顺序的方法
问题描述
我使用R语言的ggsankey包绘制了桑基图,整体效果正常,但希望调整第二层节点的排列顺序:当前节点从上到下为SD、PR、DP、CR,需改为CR、PR、SD、DP。请问是否有自定义节点位置的方法?
原代码
devtools::install_github("davidsjoberg/ggsankey") library(ggsankey) sankey_df <- base_limpia%>% transmute( Treatment = Type.of.Treatment, Response = Respuesta, Transplantation = Post_therapy_trasplantation ) sankey_df <- sankey_df %>% make_long(Treatment, Response, Transplantation ) reagg <- sankey_df%>% dplyr::group_by(node)%>% # 按节点分组统计频次 tally() sankey_df2 <- merge(sankey_df, reagg, by.x = 'node', by.y = 'node', all.x = TRUE) png(file = "Figure 6.png", width = 3200, height = 2000, res = 300) plot <- ggplot(sankey_df2, aes(x = x, next_x = next_x, node = node, next_node = next_node, fill = factor(node), label = paste0(node, " = ", n))) plot <- plot + geom_sankey(flow.alpha = 0.5, node.color = "black", show.legend = F) + geom_sankey_label(size = 3, color = "black", fill = "white") + theme_bw() + theme(legend.position = "none") + theme(axis.title = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank())
解决方案
ggsankey的节点排列顺序默认跟随对应列的因子水平或数据出现顺序,要自定义第二层(Response对应层级)的节点顺序,只需在数据预处理阶段将Response列转换为指定顺序的因子即可:
修改步骤
- 在
transmute生成sankey_df时,将Response列设置为因子,指定levels为目标顺序c("CR", "PR", "SD", "DP")。 - 后续流程保持不变,
make_long会沿用这个因子顺序生成桑基图节点。
修改后的完整代码
devtools::install_github("davidsjoberg/ggsankey") library(ggsankey) library(dplyr) sankey_df <- base_limpia %>% transmute( Treatment = Type.of.Treatment, # 关键修改:将Response设为指定顺序的因子 Response = factor(Respuesta, levels = c("CR", "PR", "SD", "DP")), Transplantation = Post_therapy_trasplantation ) sankey_df <- sankey_df %>% make_long(Treatment, Response, Transplantation ) reagg <- sankey_df %>% dplyr::group_by(node)%>% tally() sankey_df2 <- merge(sankey_df, reagg, by.x = 'node', by.y = 'node', all.x = TRUE) png(file = "Figure 6.png", width = 3200, height = 2000, res = 300) plot <- ggplot(sankey_df2, aes(x = x, next_x = next_x, node = node, next_node = next_node, fill = factor(node), label = paste0(node, " = ", n))) plot <- plot + geom_sankey(flow.alpha = 0.5, node.color = "black", show.legend = F) + geom_sankey_label(size = 3, color = "black", fill = "white") + theme_bw() + theme(legend.position = "none") + theme(axis.title = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank()) dev.off() # 关闭绘图设备
如果上述方法未生效,也可以在生成sankey_df2后,针对第二层(x=2)的节点单独设置因子顺序:
sankey_df2 <- sankey_df2 %>% mutate(node = case_when( x == 2 ~ factor(node, levels = c("CR", "PR", "SD", "DP")), TRUE ~ as.factor(node) ))
内容的提问来源于stack exchange,提问作者vaquera
相关产品推荐
相关产品推荐

