python - 带有下拉变量选择器的 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')
)
这会生成热图,但选择器没有效果。选择用于热图颜色编码的变量的正确方法是什么?
解决方案
您需要将选择分配给变量名称,并将其添加到图表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
)
推荐阅读
- javascript - 在我删除的元素上启动时无法捕获 touchmove
- python - 在 Python 中将字符串“YYYYMMDDHHMMSS”转换为时间戳
- angular - 仍然“无法绑定到 'dataSource',因为它不是 'table' 的已知属性。”
- javascript - Ramda:在 R.ifElse() 函数调用中访问输入对象的属性
- r - 在 R 中使用源、<<-、局部/全局变量和环境时出现问题
- c# - 使用 c# 将值写入已经打开的工作簿
- python - 数据帧过滤器
- docker - 在 Dockerfile 或 docker-compose 中定义环境变量?
- python - 如何将字符串类型转换为 numpy 数组?
- terraform - 如何从 Terraform 中的文件加载输入数据?