使用热阴影和文本值过滤 altair 热图

Filter altair heatmap with heat shading and text value

我正在尝试使用 Altair 库创建热图,但我希望使用不同视图的滑块来过滤我的数据。滑块适用于仅标准颜色的热图,但是当我尝试向框中添加文本以描述每个单元格中的值时,出现下面的 javascript 错误。 (在没有任何过滤器滑块的情况下,将文本添加到热图中效果很好。)

import altair as alt
import pandas as pd
source = pd.DataFrame({'year':[2017, 2017, 2018, 2018],
                       'age':[1, 2, 1, 2],
                       'y':['a', 'a', 'a', 'a'],
                       'n':[1, 2, 3, 4]})

slider = alt.binding_range(min=2017, max=2018, step=1)
select_year = alt.selection_single(name="my_year_slider", fields=['year'], bind=slider)
base = alt.Chart(source).add_selection(select_year).transform_filter(select_year)

heatmap = base.mark_rect().encode(
    x='age:O',
    y='y:O',
    color='n:Q')

text = base.mark_text(baseline='middle').encode(
    x='age:O',
    y='y:O',
    text='n:Q')

heatmap + text

这个returnsJavascript Error: Duplicate signal name: "my_year_slider_tuple"

因为您将选区添加到基本图表中,然后将它的两个副本分层,所以选区被定义了两次。解决方案是只定义一次选择;像这样:

import altair as alt
import pandas as pd
source = pd.DataFrame({'year':[2017, 2017, 2018, 2018],
                       'age':[1, 2, 1, 2],
                       'y':['a', 'a', 'a', 'a'],
                       'n':[1, 2, 3, 4]})

slider = alt.binding_range(min=2017, max=2018, step=1)
select_year = alt.selection_single(name="my_year_slider", fields=['year'], bind=slider)

base = alt.Chart(source).encode(
    x='age:O',
    y='y:O',
).transform_filter(select_year)

heatmap = base.mark_rect().encode(color='n:Q').add_selection(select_year)

text = base.mark_text(baseline='middle').encode(text='n:Q')

heatmap + text