如何根据下拉列表为图表选择数据?

时间:2020-04-01 05:13:42

标签: altair

我有一个数据框,我想根据一个下拉列表为其子集选择一组行。因此,给出以下代码:

import pandas as pd
import altair as alt
from vega_datasets import data

cars = pd.melt(data.cars(), ['Horsepower', 'Origin', 'Name', 'Year'])
cars.head()

select_box = alt.binding_select(options=list(cars['variable'].unique()))
selection = alt.selection_single(name='d_axis', fields=['variable'], bind=select_box)

alt.Chart(cars).mark_point().encode(
    x='Horsepower',
    y='value',
    color='Origin',
    tooltip='Name'
).add_selection(
    selection
).transform_filter(
    selection
)

我只希望选择Origin是“ USA”的汽车,而不是更改X值。
所以实际上是什么地方

alt.Chart(cars).mark_point().encode(

成为:

alt.Chart(cars[cars['Origin'] == selection]).mark_point().encode(

谢谢, 斯蒂芬

1 个答案:

答案 0 :(得分:1)

您可以将选择内容绑定到要过滤的字段:

import altair as alt
from vega_datasets import data

cars = data.cars()

select_box = alt.binding_select(options=list(cars['Origin'].unique()))
selection = alt.selection_single(fields=['Origin'], bind=select_box)

alt.Chart(cars).mark_point().encode(
    x='Horsepower',
    y='Miles_per_Gallon'
).add_selection(
    selection
).transform_filter(
    selection
)

enter image description here