首页 > 解决方案 > Altair 字图按年份过滤不起作用

问题描述

我在根据“年份”列值过滤数据时遇到问题。从 1950 年到 2013 年,我每年都有一个下拉菜单,当我更改下拉地图中的值时,应该使用新数据重新呈现,但事实并非如此。该地图仅呈现 2013 年(数据集中的最后一组)。

这是代码:

years = pd.unique(seasonData['year'])
seasons = ['yearAvg', 'summerAvg', 'winterAvg']
#map selector
selectorYear = alt.selection_single(
    name='Years',
    fields=['year'],
    bind=alt.binding_select(options=years, name="Year"),
    init={'year': '1951'},
)
selectorSeason = alt.selection_single(
    name='Temperature for',
    fields=['column'],
    bind=alt.binding_select(options=seasons, name="Seasons"),
    init={'column': 'yearAvg'},
)
base = alt.Chart(geoDF).mark_geoshape(
  fill = '#bfdff7', stroke = 'white', strokeWidth = 1
).transform_lookup(
    lookup='name_long',
    from_= alt.LookupData(seasonData, 'Country', ['yearAvg', 'summerAvg', 'winterAvg', 'year', 'Country'])
).transform_fold(
    seasons, as_ = ['column', 'value']
).encode(
    tooltip = [alt.Tooltip('value:Q', title='Temperature', format='.2f'), alt.Tooltip('Country:N', title='Country'), alt.Tooltip('year:N', title='year')],                                                 #-40,    -20,       0,             5,       10,       15,        20,            25,   30,         35,           40,    50
    fill = alt.Fill('value:Q', title='Avarage temperature by county', scale=alt.Scale(type="linear", domain=[-40, -20, 0, 5, 10, 15, 20, 25, 30, 35, 40, 50], range=['#00f', '#2424f7', '#2ad8ff', '#8fe0ff', '#f3ff8f', '#fff18f', '#ffc254', '#ff9354', '#ff6c54', '#fd553a', '#fd1a1a', '#f00'] )) 
).add_selection(
    selectorYear,
    selectorSeason
).transform_filter(
    selectorYear & selectorSeason
).properties(
   width = 1000, height = 650,
   title='World map of temperature data (1950 - 2013)'
)
base

以下是数据的外观:

在此处输入图像描述

以下是图表的外观: 在此处输入图像描述

如果我在下拉列表中更改年份,图表会变黑。 在此处输入图像描述

我究竟做错了什么?我怎样才能解决这个问题?

标签: pythonaltairvega-litevega

解决方案


@jakevdp的评论中描述的解决方案 有效。只需将传递给图表函数的数据框更改为传递给 LookupData 的数据框,如下所示:

base = alt.Chart(seasonData).mark_geoshape(
  fill = '#bfdff7', stroke = 'white', strokeWidth = 1
).transform_lookup(
    lookup='Country',
    # from_= alt.LookupData(seasonData, 'Country', ['yearAvg', 'summerAvg', 'winterAvg', 'year', 'Country'])
    from_= alt.LookupData(geoDF, 'name_long', ['scalerank', ...... , 'geometry'])
)

但是为了正确渲染,我需要包含(LookupData 函数的fields参数)来自 geo df 的所有字段。仅添加几何图形不起作用。


推荐阅读