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

如何在Altair森林图(forestplot)中垂直偏移误差棒避免重叠

在Altair中实现双置信区间不重叠的森林图

要在同一变量行下展示两个不重叠的置信区间,核心思路是给不同组的y轴位置添加微小偏移量,同时保持y轴刻度显示原始变量名,无需依赖分面。

完整实现代码

import altair as alt
import pandas as pd

# 构造示例数据(可替换为你的真实数据)
df = pd.DataFrame({
    "variable": ["变量1", "变量1", "变量2", "变量2", "变量3", "变量3"],
    "ci_group": ["90% CI", "95% CI"],
    "coef": [0.6, 0.55, -0.3, -0.25, 1.1, 1.0],
    "lower": [0.4, 0.3, -0.5, -0.4, 0.8, 0.7],
    "upper": [0.8, 0.8, -0.1, 0.0, 1.4, 1.3]
})

# 定义偏移量(可根据图表高度调整,建议0.1-0.3之间)
OFFSET = 0.2

# 创建误差棒图层
error_bars = alt.Chart(df).transform_calculate(
    # 为不同置信区间组添加垂直偏移
    y_shifted=f"datum.ci_group == '90% CI' ? datum.variable + {OFFSET} : datum.variable - {OFFSET}"
).mark_errorbar(width=12).encode(
    x=alt.X("coef:Q", title="回归系数"),
    xError=alt.XError("lower:Q", "upper:Q"),
    y=alt.Y(
        "y_shifted:N",
        title="变量",
        # 强制y轴刻度使用原始变量名,忽略偏移后的值
        domain=df["variable"].unique(),
        labelExpr="datum.label"
    ),
    color=alt.Color("ci_group:N", title="置信区间")
)

# 创建系数点图层
coef_points = alt.Chart(df).transform_calculate(
    y_shifted=f"datum.ci_group == '90% CI' ? datum.variable + {OFFSET} : datum.variable - {OFFSET}"
).mark_point(filled=True, size=60).encode(
    x="coef:Q",
    y="y_shifted:N",
    color="ci_group:N"
)

# 组合图层并显示
final_plot = error_bars + coef_points
final_plot.show()

关键细节说明

  1. 垂直偏移实现:通过transform_calculate给不同置信区间组的y值加上/减去固定偏移量,让两个误差棒在垂直方向上错开。
  2. y轴刻度保持:通过domain指定原始变量列表,labelExpr强制显示原始变量名,避免偏移后的值影响标签显示。
  3. 偏移量调整:OFFSET参数可根据图表高度和视觉效果灵活调整,数值太小可能仍有重叠,太大则会显得间距过宽。

这样就能实现同一变量行下两个置信区间不重叠的森林图,完全无需使用分面方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:45:20