Shapelets平台结合单选组与Altair时出现KeyError: 'return'求助
Shapelets中单选组绑定Altair图表函数触发KeyError: 'return'的解决方法
你遇到的KeyError: 'return'是因为Shapelets的组件绑定机制对函数返回值有特定要求——绑定到altair_chart组件的函数,必须直接返回Altair的Chart对象,而不是返回app.altair_chart()创建的组件实例。
修正后的代码
def print_selected_option_1(categories: dict, radio: str): melted_cat = pd.melt(categories[radio].reset_index(), id_vars=['postalCode'], var_name='Feature', value_name='Count') # Create stacked bar chart chart = alt.Chart(melted_cat).mark_bar().encode( x='postalCode:N', y='Count:Q', color='Feature:N', tooltip=['postalCode:N', 'Feature:N', 'Count:Q'] ).properties(width=600, height=400, title=f'Bar Chart by Zipcode and {radio}').interactive() # 关键修改:直接返回Altair Chart对象,而非app.altair_chart实例 return chart radiogroup = app.radio_group(list(categories.keys())) app.place(radiogroup) altair_chart = app.altair_chart() altair_chart.bind(print_selected_option_1, categories, radiogroup) app.place(altair_chart) app.register()
核心修改点
- 把原函数最后一行的
return app.altair_chart(chart=chart)改为return chart,直接返回Altair生成的图表对象 - Shapelets的
altair_chart组件在绑定函数后,会自动接收函数返回的Chart对象并渲染,不需要手动创建组件实例返回
内容的提问来源于stack exchange,提问作者Amelia Patel
相关产品推荐
相关产品推荐

