如何用单axis1元素生成美观的ggalluvial桑基图?
单Axis1元素生成美观的ggalluvial桑基图解决方案
问题背景
使用以下仅含单个出发地的数据框生成桑基图时,因axis1仅一个元素,原始代码无法呈现理想的分流效果:
df <- data.frame(departure = c("Paris"), arrival = c("Nantes","Caen","Nice"), value = c(0.5625, 0.312, 0.125))
原始代码:
df %>% group_by(departure) %>% ggplot(aes(y = value*100, axis1 = departure, axis2 = arrival)) + geom_alluvium(aes(fill = arrival), width = 1/12) + geom_stratum(width = 1/12, fill = "white", color = "grey") + geom_label(stat = "stratum", aes(label = after_stat(stratum))) + scale_x_discrete(limits = c("departure", "arrival"), expand = c(.05, .05)) + scale_fill_brewer(type = "qual", palette = "Set1") + theme(legend.position = "none")
用户曾尝试添加虚构行模拟效果,但希望无需额外数据即可实现美观的桑基图。
解决方案
无需添加虚构行,只需调整图层参数即可优化效果,以下是修改后的代码:
library(ggplot2) library(ggalluvial) df <- data.frame(departure = c("Paris"), arrival = c("Nantes","Caen","Nice"), value = c(0.5625, 0.312, 0.125)) ggplot(df, aes(y = value*100, axis1 = departure, axis2 = arrival)) + # 调整knot.pos让冲积曲线过渡更自然,可根据需求修改为0.4/0.6 geom_alluvium(aes(fill = arrival), width = 1/12, knot.pos = 0.5) + # 增大分层区块宽度,让起始节点更醒目 geom_stratum(width = 1/8, fill = "white", color = "grey") + geom_label(stat = "stratum", aes(label = after_stat(stratum))) + # 增大横向留白,避免标签与区块拥挤 scale_x_discrete(limits = c("departure", "arrival"), expand = c(.2, .2)) + scale_fill_brewer(type = "qual", palette = "Set1") + theme_minimal() + # 不需要图例可设为"none",如需展示可放底部 theme(legend.position = "none")
关键调整说明
- 移除不必要的
group_by:因departure仅一个值,分组操作无实际作用 - 调整
knot.pos:控制冲积层曲线的弯曲位置,优化分流视觉效果 - 增大
geom_stratum的width:让单个起始节点的区块更突出 - 扩大
scale_x_discrete的expand值:给两侧分层区块和标签预留足够空间
内容的提问来源于stack exchange,提问作者Chloé
相关产品推荐
相关产品推荐

