我正在尝试使用Altair lib创建一个热图,但是我正在寻找使用滑块过滤不同视图的数据的方法。滑块可以与标准的仅彩色热图配合使用,但是当我尝试向框中添加文本以描述每个单元格中的值时,出现以下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
这将返回Javascript Error: Duplicate signal name: "my_year_slider_tuple"
答案 0 :(得分:2)
因为您已将选择内容添加到基本图表中,然后分层放置了两个副本,所以选择内容定义了两次。解决的办法是只定义一次选择。像这样的东西:
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