如何在 Altair 中更改基本图表的 Y 值?

How can I chamge the Y values off a base chart in Altair?

因此致力于根据状态数据显示图表:

import requests
import pandas as pd
import altair as alt

URL = 'https://covidtracking.com/api/states/daily'
# sending get request and saving the response as response object 
r = requests.get(url = URL) 

# extracting data in json format 
data = r.json() 
df = pd.DataFrame(data)

state_box = alt.binding_select(options=list(df['state'].unique()))
selection = alt.selection_single(name='Data for', fields=['state'], bind=state_box)

chart1 = alt.Chart(df, title='Deaths').mark_bar().encode(
    x='dateChecked:T',
    y='death',
    tooltip=list(df.columns)
).add_selection(
    selection
).transform_filter(
    selection
).interactive()
chart2 = alt.Chart(df, title='Tests').mark_bar().encode(
    x='dateChecked:T',
    y='totalTestResults',
    tooltip=list(df.columns)
).add_selection(
    selection
).transform_filter(
    selection
).interactive()

(chart1 | chart2)

而且我正在使用重复代码。如何重用 chart1 的定义并简单地更改 y 值,所以在伪代码中:

chart2 = chart1.set_y('totalTestResults')

好的,明白了。所以首先我用所有常用参数设置我的 "base" 图表:

base = alt.Chart(df).mark_line().encode(
    x='dateChecked:T',
    tooltip=list(df.columns)
).add_selection(
    selection
).transform_filter(
    selection
).interactive()

然后添加我需要更改的编码和属性:

chart1 = base.encode(y='hospitalizedIncrease').properties(title='hospitalizedIncrease')
chart2 = base.encode(y='death:Q').properties(title='Deaths')

然后播放:)

(chart1 | chart2)

还想出了如何初始化我的选择,方法是将 init 添加到 selection_single::

state_box = alt.binding_select(options=list(df['state'].unique()))
selection = alt.selection_single(name='Data for', fields=['state'], bind=state_box, init={'state': 'NY'})

A​​ltair 的所有图表方法return 原始图表的修改副本。这意味着您可以随时执行以下操作:

chart1 = alt.Chart(data).mark_point().encode(
  x='x:Q',
  y='y1:Q',
)

chart2 = chart1.encode(y='y2:Q')

chart1 | chart2

在这种情况下,chart2 将具有与 chart1 相同的所有属性,除了更新的 y 编码,并且 chart1 将不会被新编码修改。