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

如何调整ggalluvial桑基图的标签位置与黑色层样式?

解决ggalluvial桑基图的三个定制需求

针对你提出的三个需求,我们可以通过调整原代码参数、修正小错误来实现:

需求对应修改点

  1. 将流的标签置于图的下方:通过theme调整x轴标题的位置,让其更靠下;若不需要总标题也可直接隐藏。
  2. 加宽黑色stratum(层)的宽度:修改geom_stratum的width参数,增大数值即可(原代码为1/12,可改为1/6或0.2这类更大的值)。
  3. 将层的标签放置在黑色柱体的中间位置:给geom_label添加position = position_stack(vjust = 0.5),让标签垂直居中在柱体内部;同时调整标签样式,避免遮挡黑色柱体。

修改后的完整代码

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

df <- data.frame(status = c("open", "close", "close", "open/close", "close"), 
                 stock = c("google", "amazon", "amazon", "yahoo", "amazon"), 
                 newspaper = c("times", "newyork", "london", "times", "times"))

# 统计每个组合的出现次数,添加.groups避免dplyr警告
df <- df %>% 
  dplyr::group_by(stock, newspaper, status) %>% 
  summarise(n = n(), .groups = "drop") 

# 定义因子水平
df$status <- factor(df$status, levels = c("open", "open/close", "close"))
df$stock <- factor(df$stock, levels = c("google", "amazon", "yahoo"))
df$newspaper <- factor(df$newspaper, levels = c("times", "newyork", "london"))

# 绘制定制化桑基图
ggplot(df, aes(y = n, axis1 = stock, axis2 = newspaper)) +
  geom_alluvium(aes(fill = status), width = 1/12) +
  # 加宽黑色层的宽度
  geom_stratum(width = 1/6, fill = "black", color = "grey") +
  # 标签居中在黑色柱体,设置白色文字+透明填充更清晰
  geom_label(stat = "stratum", aes(label = after_stat(stratum)),
             position = position_stack(vjust = 0.5), fill = NA, color = "white") +
  scale_x_discrete(limits = c("stock", "newspaper"), expand = c(.05, .05)) +
  scale_fill_brewer(type = "qual", palette = "Set1") +
  # 将x轴标题移至图下方(若不需要可改为element_blank()隐藏)
  theme(axis.title.x = element_text(vjust = -2, size = 12))

补充说明

  • 修正了原代码中ggplot(df.2, ...)的错误,改为ggplot(df, ...);
  • position_stack(vjust = 0.5)确保标签精准落在黑色柱体的垂直中心;
  • 若不需要x轴总标题,可将theme中的axis.title.x设置为element_blank()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:10:35