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

如何在ggforce平行集图中调整右侧节点的Y轴位置

解决ggforce平行集图右侧节点居中对齐问题

要实现左侧流带居中对齐右侧节点,核心是调整右侧节点的y轴位置,让其与左侧所有流带的总中心对齐。具体步骤如下:

  1. 计算偏移量:先算出所有权重的总和,偏移量取总和的一半,确保右侧节点的中心与左侧流带的总中心重合。
  2. 调整数据中的y值:仅对右侧(outcome)的行修改y值,加上偏移量实现整体上移。
  3. 重新绘制图表:用调整后的数据绘图,流带会自动连接到偏移后的右侧节点。

修改后的完整代码:

# load libraries
library(tidyverse)
library(ggforce)

# create example data frame
example_data <- tibble::tribble(
  ~predictor,    ~outcome, ~weight,  ~color1, ~color2,
    "pred_1", "outcome_1",    0.05, "#49B5AE", "#FF5E2B",
    "pred_2", "outcome_1",    0.32, "#49B5AE", "#FF5E2B",
    "pred_3", "outcome_1",    0.22, "#49B5AE", "#FF5E2B",
    "pred_4", "outcome_1",    0.13, "#37B4FF", "#FF5E2B",
    "pred_5", "outcome_1",    0.17, "#37B4FF", "#FF5E2B",
    "pred_6", "outcome_1",    0.11, "#37B4FF", "#FF5E2B"
  )

# 计算总权重与偏移量
sum_weight <- sum(example_data$weight)
nudge_y <- sum_weight / 2

# 创建alluvial数据并调整右侧节点位置
alluvial <- example_data |>
  gather_set_data(c("predictor", "outcome")) |>
  mutate(x = factor(x, levels = c("predictor", "outcome")),
         # 仅对右侧outcome的行添加y偏移
         y = ifelse(x == "outcome", y + nudge_y, y))

# 设置轴宽和间距参数
aw <- 0.05
sp <- 0.25

# 绘制可视化图表
ggplot(alluvial, aes(x = x, id = id, split = y, value = weight)) +
  geom_parallel_sets(aes(fill = I(fct_rev(color1))),
                     axis.width = aw, sep = sp) +
  geom_parallel_sets_labels(data = alluvial |> filter(x == "predictor"),
                            aes(color = I(color1)), 
                            size = 3, angle = 0, hjust = 1,
                            axis.width = aw, sep = sp) +
  geom_parallel_sets_labels(data = alluvial |> filter(x == "outcome"),
                            aes(color = I(color2)), 
                            size = 3, angle = 0, hjust = 0, fontface = "bold",
                            axis.width = aw, sep = sp) +
  theme_void()

原理说明

  • 左侧流带的总高度等于所有权重之和(此处为1),中心位置在sum_weight/2(即0.5)。
  • 通过给右侧节点的y值加上偏移量,让右侧节点的中心也落在0.5位置,从而实现左侧流带与右侧节点的居中对齐。
  • 该方法仅调整右侧节点及对应流带终点的位置,不会移动整个图表,精准匹配需求。

内容的提问来源于stack exchange,提问作者Natalie O'Shea

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:35:34