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

Altair双轴图表如何实现不同图层数据源的单独过滤?

Altair双轴图表不同图层单独过滤数据源的实现方法

核心逻辑:resolve_scale是图层组合对象的方法,不能作用于单个独立的Altair图表实例,需要在两个图层完成叠加后调用该方法即可实现双Y轴效果,不同图层可以使用完全独立的过滤后数据源。

完整可运行代码

import altair as alt
from vega_datasets import data
source = data.seattle_weather()

# 降水量图层:仅使用天气为rain的过滤后数据
chart_precip = alt.Chart(source.query("weather == 'rain'")).mark_line(color='blue', size=1).encode(
    x=alt.X('date:T', axis=alt.Axis(title='日期'), scale=alt.Scale(zero=False)),
    y=alt.Y('mean(precipitation)', axis=alt.Axis(title='平均降水量', titleColor='blue'))
).properties(width=500, height=300)

# 最高温图层:仅使用天气不为rain的过滤后数据
chart_temp = alt.Chart(source.query("weather != 'rain'")).mark_line(color='red', size=1).encode(
    x='date:T',
    y=alt.Y('mean(temp_max)', axis=alt.Axis(title='平均最高温', titleColor='red'))
)

# 图层叠加后设置Y轴独立分辨率,即可正常显示双Y轴标签
(chart_precip + chart_temp).resolve_scale(y='independent')

补充说明

  • 代码中为两个Y轴分别配置了和折线同色的标题,可直观区分数据对应的坐标轴
  • 无需在每个子图层重复设置宽高属性,第一个图层的properties配置会自动沿用到整个组合图表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:06:03