首页 > 解决方案 > 带有下拉变量选择器的 Altair 热图

问题描述

考虑这个玩具数据集:

import pandas as pd
import altair as alt

df = pd.read_json('https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/cars.json')
df = df.groupby(['Origin', 'Year'])[['Miles_per_Gallon', 'Weight_in_lbs', 'Displacement']].mean().reset_index()
df = pd.melt(df, id_vars=['Origin', 'Year'], value_vars=['Miles_per_Gallon', 'Weight_in_lbs', 'Displacement'])
df.head()


    Origin  Year    variable    value
0   Europe  1970-01-01  Miles_per_Gallon    25.20
1   Europe  1971-01-01  Miles_per_Gallon    28.75
2   Europe  1972-01-01  Miles_per_Gallon    22.00
3   Europe  1973-01-01  Miles_per_Gallon    24.00
4   Europe  1974-01-01  Miles_per_Gallon    27.00

我想制作一个热图,我可以在其中选择要对填充颜色进行编码的变量。从文档来看,这似乎可行,因为下拉选择器会根据所选变量对 df 进行子集化:

dropdown = alt.binding_select(options=list(df.variable.drop_duplicates()))
alt.Chart(df).mark_rect().encode(
    x='Origin:N', 
    y='Year:T', 
    color='value:Q',
).add_selection(
    alt.selection_single(fields=['variable'], bind=dropdown, name='Select')
)

这会生成热图,但选择器没有效果。选择用于热图颜色编码的变量的正确方法是什么?

在此处输入图像描述

标签: pythonaltair

解决方案


您需要将选择分配给变量名称,并将其添加到图表add_selection中,并通过绑定它以过滤数据transform_filter

dropdown = alt.binding_select(options=list(df.variable.drop_duplicates()))
selection = alt.selection_single(fields=['variable'], bind=dropdown, name='Select')

alt.Chart(df).mark_rect().encode(
    x='Origin:N', 
    y='Year:T', 
    color='value:Q',
).add_selection(
    selection
).transform_filter(
    selection
)

推荐阅读