【发布时间】: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