【问题标题】:Dual Axis on Altair - filtering sourceAltair 上的双轴 - 过滤源
【发布时间】:2021-10-18 17:49:04
【问题描述】:

Altair 图表在 Python 中非常出色,因为它很容易添加悬停数据注释(与 Seaborn 不同),并且添加额外的“标记”(线条、条形等)比 Plotly 更干净,但有一个问题是双轴。这通常可以正常工作(类似于文档https://altair-viz.github.io/gallery/layered_chart_with_dual_axis.html):

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

chart_base = alt.Chart(source.query("weather != 'snow'")).encode(
    alt.X('date:T',
    axis=alt.Axis(),
    scale=alt.Scale(zero=False)
    )
).properties(width=800, height=400)

line_prec = chart_base.mark_line(color='blue', size=1).encode(y='mean(precipitation)')
line_temp = chart_base.mark_line(color='red', size=1).encode(y='mean(temp_max)')
alt.layer(line_prec, line_temp).resolve_scale(y='independent')

...所以我需要做的就是过滤各个标记,类似于 source.query 但说我们只想在“weather =='rain'”和 temp_max 在“weather!='rain '"(是的,分析上没有洞察力,只是为了说明双过滤器的工作示例)。

解决方案可能是Altair combining multiple data sets,但 DRYer 代码不是双轴代码,更有希望,但多层方法似乎不适用于双轴,因为我们尝试添加(相当拼命地).resolve_scale 时出错(y='独立'):

chart_precip = alt.Chart(source.query("weather == 'rain'")).mark_line(color='blue', size=1).encode(
    y='mean(precipitation)', 
    x=('date:T')
).properties(width=500, height=300) #.resolve_scale(y='independent') # can't add resolve_scale

chart_temp = alt.Chart(source.query("weather != 'rain'")).mark_line(color='red', size=1).encode(
    y='mean(temp_max)', 
    x=('date:T')
).properties(width=500, height=300) #.resolve_scale(y='independent') # can't add resolve_scale

chart_precip + chart_temp

有效但不标注双轴,不好:

那么...有没有办法简单地单独过滤双轴标记?

【问题讨论】:

    标签: python plot axes altair vega-lite


    【解决方案1】:

    您可以通过在分层图表而不是单个图层上设置resolve_scale(y='independent')来实现双轴:

    (chart_precip + chart_temp).resolve_scale(y='independent')
    

    请注意,chart_precip + chart_temp 只是 alt.layer(chart_precip, chart_temp) 的简写,因此这与您的第一个示例非常相似。

    【讨论】:

    • 宾果游戏!感谢@jakevdp,这是一种享受——我怀疑你们已经设计了 Altair 来处理它。也许更新文档以使用 alt.layer(chart1, chart2) 而不是 chart1 + chart2 虽然方便快捷,前者显示了更深层次的对象来整理并阻止像我这样的厚厚的人想知道如何组合双轴!
    猜你喜欢
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2021-10-06
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多