如何在ggsankey桑基图中兼顾正确标签与流大小?
解决方案:ggsankey桑基图标签与流大小同时正确
问题根源在于原数据中同一节点对应多条流向记录:当映射value时,geom_sankey能正确计算流量,但geom_sankey_label会为每条记录生成标签,导致重复;去掉value映射后标签正常,但流量计算失效。
解决步骤:
- 提取唯一节点信息:从原数据中筛选出每个阶段(x)与节点(node)的唯一组合,确保每个节点仅对应一条记录。
- 绘图时,主数据流保留
value映射保证流量正确,给geom_sankey_label单独指定唯一节点数据集,避免标签重复。
完整代码:
# Import packages library(tidyverse) library(ggsankey) # create data test <- tibble( x = factor(c("Production", "Production", "Production", "Production", "Production", "Production", "Transport", "Transport", "Consumption", "Consumption"), levels = c("Production", "Transport", "Consumption")), node = c("Product A", "Product B", "Product A", "Product B", "Product A", "Product B", "Transport", "Transport", "Sector I", "Sector II"), next_x = factor(c("Transport", "Transport", "Consumption", "Consumption", "Consumption", "Consumption", "Consumption", "Consumption", NA_character_, NA_character_), levels = c("Production", "Transport", "Consumption", NA_character_)), next_node = c("Transport", "Transport", "Sector I", "Sector I", "Sector II", "Sector II", "Sector I", "Sector II", NA_character_, NA_character_), value = c(1323, 1159, 5070, 2554, 461, 2758, 1768, 713, 9392, 3932) ) # 提取唯一节点数据集(每个x+node组合仅保留一条) node_labels <- test %>% distinct(x, node) %>% drop_na() # 绘制桑基图 ggplot(test, aes(x = x, next_x = next_x, node = node, next_node = next_node, value = value, fill = factor(node))) + geom_sankey(flow.alpha = .6, color = "gray30") + # 单独指定标签用的数据集,确保每个节点只显示一次 geom_sankey_label(data = node_labels, aes(label = node), size = 3, color = "white", fill = "gray40") + scale_fill_viridis_d(drop = FALSE) + theme_sankey(base_size = 18) + labs(x = NULL) + theme(legend.position = "none", axis.text.x = element_blank(), plot.title = element_text(hjust = .5)) + ggtitle("Massflow")
效果说明:
- 主数据集
test保留value映射,geom_sankey会根据每条记录的value计算流的宽度,流量大小完全匹配数据。 geom_sankey_label使用node_labels数据集,每个节点在对应阶段仅绘制一次标签,解决重复问题。
内容的提问来源于stack exchange,提问作者Hugo
相关产品推荐
相关产品推荐

