该示例展示了如何创建一个带下拉菜单变量选择器的Altair热度图。
首先,我们来看一下原始代码:
import altair as alt
from vega_datasets import data
source = data.crime_heatmap.url
# Define the string of possible values
fields = ['total', 'property', 'violent', 'vehicle', 'burglary']
# Define the chart
heatmap = alt.Chart(source).mark_rect().encode(
alt.X('year(date):O', title=None),
alt.Y('month(date):O', title=None),
alt.Color('sum(crimes):Q', scale=alt.Scale(scheme='yellowgreenblue')),
).properties(
width=600,
height=300,
title='Monthly Crime Heatmap'
)
# Define the dropdown selector
field_dropdown = alt.binding_select(options=fields)
field_select = alt.selection_single(fields='total', bind=field_dropdown, name='Crime Type')
# Define the updated chart
heatmap_select = heatmap.transform_filter(
field_select
).properties(
title='Monthly Crime Heatmap by Crime Type'
)
# Combine the two charts
alt.hconcat(
heatmap_select,
field_select
)
现在,我们对其进行翻译和本地化,使其更适合中文环境。
首先,我们需要导入必要的库:
import altair as alt
from vega_datasets import data
然后,我们加载数据集:
source = data.crime_heatmap.url
定义可能的分类变量所含的字符串如下:
fields = ['总计', '财产犯罪', '暴力犯罪', '车辆犯罪', '入室盗窃']
然后,我们定义热度图:
heatmap = alt.Chart(source).mark_rect().encode(
alt.X('year(date):O', title=None),
alt.Y('month(date):O', title=None),
alt.Color('sum(crimes):Q', scale=alt.Scale(scheme='yellowgreenblue')),
).properties(
width=600,
height=300,
title='月犯罪交叉热度图'
)
定义下拉选择框:
field_dropdown = alt.binding_select(options=fields)
field_select = alt.selection_single(fields='total', bind=field_dropdown, name='犯罪类型')