使用Altair为Gapminder数据集创建滑块时遇Schema验证错误
解决Altair中Gapminder年份滑块的初始化错误
你遇到的错误是因为selection_single的init参数格式不符合要求。当用bind=alt.binding_range绑定滑块时,单字段选择的init应该直接传入字段对应的数值,而非嵌套字典。
错误原因
原代码里init={"year": 1955}采用了字典格式,但对于绑定range滑块的单字段选择,Altair期望init是单一的字段值(这里就是年份数字),而非键值对结构。
修正后的代码
将init={"year": 1955}改为init=1955即可,完整代码如下:
import pandas as pd import altair as alt from vega_datasets import data df = data.gapminder() yearslider = alt.selection_single( name="Year", field="year", init=1955, # 改为单一数值格式 bind=alt.binding_range(min=1955, max=2005, step=5) ) alt.Chart(df).mark_circle().encode( alt.X("fertility:Q", title=None, scale=alt.Scale(zero=False)), alt.Y("life_expect:Q", title="Life expectancy", scale=alt.Scale(zero=False)), alt.Size("pop:Q", scale=alt.Scale(range=[0, 1000]), legend=alt.Legend(orient="bottom")), alt.Color("cluster:N", legend=None), alt.Shape("cluster:N"), alt.Order("pop:Q", sort="descending"), tooltip=['country:N'], ).configure_view(fill="#fff").properties(title="Number of children by mother").interactive().add_selector(yearslider).transform_filter(yearslider)
说明
修改后,滑块会默认初始化到1955年,拖动滑块时图表会自动过滤对应年份的数据,其余配置无需改动即可正常运行。
内容的提问来源于stack exchange,提问作者elksie5000
相关产品推荐
相关产品推荐

