使用Altair保存带标签柱状图时遇SchemaValidationError问题咨询
问题描述
我运行Altair官方文档中的带标签柱状图示例代码:
import altair as alt from vega_datasets import data source = data.wheat() base = alt.Chart(source).encode( x='wheat', y="year:O", text='wheat' ) base.mark_bar() + base.mark_text(align='left', dx=2)
添加保存PNG的代码后:
base.save('/path/to/chart.png')
出现错误:
altair.utils.schemapi.SchemaValidationError: '{'data': {'name':
'data-76d1ce26ea5761007c35827e1564d86c'}, 'encoding': {'text':
{'field': 'wheat', 'type': 'quantitative'}, 'x': {'field': 'wheat',
'type': 'quantitative'}, 'y': {'field': 'year', 'type': 'ordinal'}}}'
is an invalid value.'mark' is a required property
请问这是Altair的bug还是我的操作有误?
解决方案
这是操作有误,并非Altair的bug。
问题出在你保存的base对象只是一个包含数据和编码配置的基础Chart模板,没有指定任何标记(mark)类型,不符合Vega-Lite图表的Schema要求,所以报错提示mark是必填属性。
你需要保存的是组合后的完整图表,也就是base.mark_bar() + base.mark_text(align='left', dx=2)这个对象。正确代码如下:
import altair as alt from vega_datasets import data source = data.wheat() base = alt.Chart(source).encode( x='wheat', y="year:O", text='wheat' ) # 将组合后的完整图表赋值给变量 chart = base.mark_bar() + base.mark_text(align='left', dx=2) # 保存完整图表 chart.save('/path/to/chart.png')
简单来说,base是用于复用配置的中间对象,不是可渲染的完整图表;只有添加mark_*方法并完成组合后的结果,才是具备完整结构、可以保存和展示的图表。
内容的提问来源于stack exchange,提问作者JaSON
相关产品推荐
相关产品推荐

