You need to enable JavaScript to run this app. 如何使用Altair对齐多个并排图表的X轴标题
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Altair对齐多个并排图表的X轴标题

解决方案

你可以通过以下两种方法实现X轴标题垂直对齐:

  • 方法1:直接调整第三张图表X轴标题的偏移量
    你可以在第三张图的alt.X配置中添加titleOffset参数,手动调整标题的垂直位置,测试不同数值直到和前两张对齐即可,参考修改代码:
test = base3.mark_bar(opacity=1,size=50).encode(
    y=alt.Y('time', title='',axis=alt.Axis(orient='right')),
    # 新增axis配置调整titleOffset,数值可根据实际效果微调
    x=alt.X('value', title="Autres",scale=alt.Scale(domain=(0, 40)),stack=None, axis=alt.Axis(titleOffset=18)),
    color=alt.Color('Reseau_pat:O',
                    scale=alt.Scale(domain=domain, range=range_),
                   ),
    tooltip = ['value']
).transform_filter(
    selector
)
  • 方法2:统一设置三张图表的内边距
    给三张图表的properties配置中添加完全相同的padding参数,固定三张图的上下预留空间,从根源保证绘图区域位置一致,X轴标题自然对齐,参考修改:
base = alt.Chart(data).properties(
    width=250,
    height=250,
    # 上下左右边距统一设置,数值可根据需求调整
    padding=alt.Padding(top=10, bottom=35, left=10, right=10)
).add_selection(selector)
# base2和base3都添加完全相同的padding配置即可
base2 = alt.Chart(data.loc[data.time.isin(l1)]).properties(
    width=250,
    height=250,
    padding=alt.Padding(top=10, bottom=35, left=10, right=10)
).add_selection(selector)
base3 = alt.Chart(data.loc[data.time.isin(l2)]).properties(
    width=250,
    height=250,
    padding=alt.Padding(top=10, bottom=35, left=10, right=10)
).add_selection(selector)

如果同时存在图例高度不一致的问题,你可以在拼接图表后添加resolve_scale(color='shared')将图例合并,再通过configure_legend()将图例统一放置在顶部或底部,避免图例占用高度导致的图表错位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 20:18:00