如何为三列异变量冲积图各轴配置ggrepel标签对齐规则
解决方案
核心原理
ggalluvial的stat = "stratum在计算时会自动为每个层级生成对应的x统计值,三列轴的x值分别对应1(左轴region)、2(中轴supplySector)、3(右轴demandSector)。你只需要通过after_stat(x)判断当前标签所属的轴,分层添加三个geom_text_repel分别配置规则即可。
你之前的写法失效是因为colnames(df) == "region"返回的是长度为3的布尔向量,和绘图用的层级数据长度不匹配,无法正确映射标签。
完整实现代码
library(ggplot2) library(ggrepel) library(dplyr) df <- data.frame(region = c("A","A","A","B","B","B"), supplySector = c("coal","gas","wind","coal","gas","wind"), demandSector = c("resid","indus","ag","resid","indus","ag"), Freq = 20*runif(6)); df p<- ggplot(df, aes(y = Freq, axis1 = region, axis2 = supplySector, axis3=demandSector)) + ggalluvial::geom_alluvium(aes(fill = demandSector), width = 1/12, color="black", alpha=0.8) + ggalluvial::geom_stratum(width = 1/3, fill = "grey70", color = "grey10", alpha=1) + # 左轴标签:对齐到轴左侧 geom_text_repel( aes(label = after_stat(ifelse(x == 1, stratum, NA_character_))), stat = "stratum", size = 4, direction = "y", nudge_x = -0.4, hjust = 1, segment.size = 0 ) + # 中轴标签:保留在轴内 geom_text_repel( aes(label = after_stat(ifelse(x == 2, stratum, NA_character_))), stat = "stratum", size = 4, direction = "y", nudge_x = 0, segment.size = 0 ) + # 右轴标签:对齐到轴右侧 geom_text_repel( aes(label = after_stat(ifelse(x == 3, stratum, NA_character_))), stat = "stratum", size = 4, direction = "y", nudge_x = 0.4, hjust = 0, segment.size = 0 ) + scale_x_discrete(limits = c("Region", "Supply Sector", "Demand Sector"), expand = c(0.3,0),drop=F) + scale_y_continuous("Frequency (n)")+ theme_classic()+ theme(legend.position = "none") p
参数调整说明
- 可修改
nudge_x的数值调整标签和轴之间的距离 - 如果需要保留标签和层级之间的引导线,删掉
segment.size = 0的配置即可 - 如果担心层级过小标签重叠,可以调整
min.segment.length、force等ggrepel原生参数优化效果
内容的提问来源于stack exchange,提问作者hendrik
相关产品推荐
相关产品推荐

