使用 ggsankey 重新排列桑基图中节点的顺序

问题描述 投票:0回答:1

我使用 ggsankey 包在 R 中做了一个桑基图,一切都很好,唯一的细节是我想重新调整第二级节点的顺序(现在它从上到下排列为 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)%>%  # Here we are grouping the data by node and then we are taking the frequency of it 
  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())
r ggplot2 statistics sankey-diagram
1个回答
0
投票

我没有你的数据集,所以我无法准确检查这是否有效,但当我想更改顺序时,它对我有用:将节点和/或 next_node 更改为因子并手动设置因子级别。

请参阅 github 上的示例:

dflong$node <- factor(dflong$node,levels = c("C","B","A"))
dflong$next_node <- factor(dflong$next_node,levels = c("C","B","A"))

dflong %>%
  ggplot( aes(x = x, 
              next_x = next_x, 
              node = node, 
              next_node = next_node,
              fill = factor(node),
              value = value)) +
  geom_sankey()

这对我有用,因为我的数据的节点和 next_node 也具有相同的级别,如示例中所示。

© www.soinside.com 2019 - 2024. All rights reserved.