You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整ggalluvial图中stratum框位置使其对齐图表边缘

调整ggalluvial中层(stratum)框对齐图表边缘的方法

问题

我希望将ggalluvial绘图中的stratum(层)框对齐到图表边缘,但找不到相应的自定义方法。尝试使用hjust调整位置,但它仅移动文本,无法改变框的位置。我的代码如下:

library(dplyr)
library(ggplot2)
library(ggalluvial)

alluv2 <- nplus %>%
  group_by(dpth_loc.factor, N_post_CNA.factor) %>%
  summarise(obs=n(), .groups="keep") %>%
  ggplot(aes(y=obs,
             axis1=dpth_loc.factor,
             axis2=N_post_CNA.factor)) +
  geom_alluvium(aes(fill=N_post_CNA.factor))+
  geom_stratum(width=1/4, alpha =0.8)+
  geom_text(stat = "stratum",
            aes(label = after_stat(stratum))) +
  scale_x_discrete(limits = c("Depth Location", "N post NAC Status"),
                   expand = c(0.15, 0.09)) +
  scale_fill_manual(values  = c("#d4d5b3", "#60436e")) +
  theme_minimal()+
  theme(legend.position="none",
        axis.text.x = element_text(size = 12, face = "bold"), 
        axis.title.y = element_blank())

生成的图表中,左右两侧的层框与图表边缘存在明显空白,未对齐。

解决方案

要让stratum框对齐图表边缘,需调整轴的扩展参数并偏移层框位置,具体修改如下:

修改后完整代码

library(dplyr)
library(ggplot2)
library(ggalluvial)

alluv2 <- nplus %>%
  group_by(dpth_loc.factor, N_post_CNA.factor) %>%
  summarise(obs=n(), .groups="keep") %>%
  ggplot(aes(y=obs,
             axis1=dpth_loc.factor,
             axis2=N_post_CNA.factor)) +
  geom_alluvium(aes(fill=N_post_CNA.factor))+
  # 根据层宽偏移位置,偏移量为层宽的一半
  geom_stratum(width=1/4, alpha=0.8, 
               position=position_nudge(x=c(-0.125, 0.125)))+
  # 文本同步偏移,保持与层框对应
  geom_text(stat="stratum",
            aes(label=after_stat(stratum)),
            position=position_nudge(x=c(-0.125, 0.125))) +
  scale_x_discrete(limits=c("Depth Location", "N post NAC Status"),
                   expand=c(0, 0)) +  # 移除轴两侧默认空白
  scale_fill_manual(values=c("#d4d5b3", "#60436e")) +
  theme_minimal()+
  theme(legend.position="none",
        axis.text.x=element_text(size=12, face="bold"), 
        axis.title.y=element_blank())

关键修改说明

  1. 移除轴两侧空白:将scale_x_discrete的expand参数设为c(0, 0),让x轴的起点和终点紧贴图表边缘。
  2. 偏移层框位置:使用position_nudge对geom_stratum和geom_text进行偏移,偏移量为层宽的一半(这里层宽是1/4,所以偏移0.125),确保层框边缘刚好对齐图表边缘。
  3. 同步文本偏移:文本需和层框同步偏移,避免出现文本与层框错位的情况。

如果后续调整了geom_stratum的width参数,只需将偏移量改为width/2即可保持对齐效果。

内容的提问来源于stack exchange,提问作者caroma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:35:40