【发布时间】:2021-05-18 19:56:34
【问题描述】:
考虑这个玩具数据集:
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')
)
这会生成一个热图,但选择器没有效果。选择用于热图颜色编码的变量的正确方法是什么?
【问题讨论】: