python - 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
以下是数据的外观:
我究竟做错了什么?我怎样才能解决这个问题?
解决方案
@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 的所有字段。仅添加几何图形不起作用。
推荐阅读
- mysql - SQL如何计算每个字段的表
- google-apps-script - OAuth2 同意屏幕警告 - 谷歌需要验证范围 https://www.googleapis.com/auth/script.external_request
- node.js - 如何防止节点 js 文件使用其 url 访问(读取)?
- intellij-idea - 带有 IntelliJ 的 Cucumber 找不到步骤定义
- java - 如何从 Guava 17 中替换 Guava new MapMaker().softValues().makeMap()
- c# - 如何将列值存储到数据流任务中的变量中?
- ruby - '?' 的单字母字符串表示
- dart - 无法使用 Flutter-Share 插件附加文件
- mysql - golang sql.open() 期望 0 个参数得到 1
- regex - 正则表达式替换 ;" 和 "; 之间的所有换行符