ggalluvial绘图如何增加分类间距且保证流层与柱层对齐
ggalluvial冲积图层间留白对齐解决方案
问题原因
你之前通过设置geom_stratum的白色粗边框实现间隔的方法会导致柱层向外扩张,而流层的位置计算没有匹配调整,因此出现错位。
可行方案
直接使用ggalluvial内置的gap.width参数即可实现层间留白,且能保证流层、柱层、文字标签自动对齐:
完整代码
library(ggplot2) library(ggalluvial) # 数据预处理和原有逻辑一致 data(vaccinations) vaccinations$response <- factor(vaccinations$response, rev(levels(vaccinations$response))) ggplot(vaccinations, aes(x = survey, stratum = response, alluvium = subject, y = freq, fill = response)) + geom_flow(curve_type = "cubic", gap.width = 0.08) + geom_stratum(gap.width = 0.08) + geom_text(stat = "stratum", aes(label = round(after_stat(prop), 3)), gap.width = 0.08) + theme(axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank(), panel.background = element_blank())
参数说明
gap.width取值范围为0-1,代表层间间隙占对应x轴位置总高度的比例,数值越大留白越宽,可根据视觉需求调整为0.05-0.15之间的数值- 必须给
geom_flow、geom_stratum、geom_text三个图层都设置相同的gap.width值,才能保证所有元素位置对齐
内容的提问来源于stack exchange,提问作者Ahdee
相关产品推荐
相关产品推荐

