ggalluvial绘图标签重复,如何移除右侧外部百分比标签?
解决ggalluvial右侧外部百分比标签重复的问题
你遇到的右侧外部百分比标签重复问题,是因为geom_text(stat = "flow")默认会为所有flow相关位置生成标签,包括超出axis2外侧的部分。可以通过过滤标签显示位置来解决,以下是两种简单可行的方法:
方法1:添加filter条件过滤位置
在geom_text(stat = "flow")中加入filter参数,只保留axis1到axis2之间的flow标签(即x小于2的部分):
ggplot(bdd_1, aes(axis1 = Group_year1, axis2 = Group_year2, y=freq, label = scales::percent(round(nombre, digits = 2))))+ geom_alluvium(color= "black",aes(fill=statut)) + geom_stratum() + geom_text(stat = "stratum", aes(label = after_stat(stratum)),size = 3,discern=FALSE)+ geom_text(stat = "flow", nudge_x = 0.2, size = 2.5, filter = after_stat(x < 2)) + # 新增过滤条件,移除右侧外部标签 theme(legend.position = "bottom")
方法2:避免全局label继承,单独设置并过滤
把全局aes中的label移到geom_text(stat = "flow")内单独设置,同时添加过滤条件,避免不必要的属性继承:
ggplot(bdd_1, aes(axis1 = Group_year1, axis2 = Group_year2, y=freq))+ geom_alluvium(color= "black",aes(fill=statut)) + geom_stratum() + geom_text(stat = "stratum", aes(label = after_stat(stratum)),size = 3,discern=FALSE)+ geom_text(stat = "flow", aes(label = scales::percent(round(nombre, digits = 2))), nudge_x = 0.2, size = 2.5, filter = after_stat(x < 2)) + theme(legend.position = "bottom")
原理说明
stat="flow"生成的标签会附带x位置变量:axis1对应x=1,axis2对应x=2,flow的中间位置是x=1.5。通过filter = after_stat(x < 2)可以过滤掉所有x≥2的标签,也就是你需要移除的右侧外部重复标签。
内容的提问来源于stack exchange,提问作者Chloé
相关产品推荐
相关产品推荐

