Altair加载Vega-Lite规范报错:Only chart objects can be used in RepeatChart
解决Altair加载Vega-Lite规范时的RepeatChart报错问题
问题描述
我将一些Vega-Lite规范存储在CSV中,读取为字符串并转换为JSON后,用Altair展示。大部分规范能正常运行,但部分会触发报错:ValueError: Only chart objects can be used in RepeatChart。触发报错的代码如下:
import json import altair as alt spec_str= '''{"$schema": "https://vega.github.io/schema/vega-lite/v3.json", "data": {"url": "https://raw.githubusercontent.com/nlvcorpus/nlvcorpus.github.io/main/datasets/movies.csv"}, "mark": {"type": "bar", "tooltip": null}, "encoding": {"column": {"field": "Content Rating", "type": "ordinal"}, "x": {"field": "Creative Type", "scale": {"rangeStep": 15}, "type": "nominal", "axis": {"title": "", "labels": false, "ticks": false}}, "y": {"aggregate": "mean", "field": "Production Budget", "type": "quantitative", "axis": {"title": "AVG (Production Budget)", "format": "~s"}}, "color": {"field": "Creative Type", "type": "nominal"}}}''' jsonspec = json.loads(spec_str) chart = alt.Chart.from_dict(jsonspec, validate=False)
该规范在Vega编辑器中可正常渲染,同时我还有一个可正常运行的对比规范。现寻求修复报错的方法,或其他加载Vega-Lite规范到Python的替代方式。
修复方法及替代方案
1. 升级Vega-Lite版本
问题根源是Altair对Vega-Lite v3的分面(column/row)解析逻辑存在兼容性问题,v3的分面结构易被误识别为RepeatChart。将规范中的$schema版本升级到v4或更高即可解决:
# 修改schema版本 spec_str = spec_str.replace( "https://vega.github.io/schema/vega-lite/v3.json", "https://vega.github.io/schema/vega-lite/v4.json" ) # 重新加载 jsonspec = json.loads(spec_str) chart = alt.Chart.from_dict(jsonspec, validate=False)
2. 手动用Altair API构建图表
跳过直接解析JSON的步骤,将规范拆解后用Altair原生API重新构建图表,彻底避免解析冲突:
import altair as alt import pandas as pd # 加载数据集 df = pd.read_csv("https://raw.githubusercontent.com/nlvcorpus/nlvcorpus.github.io/main/datasets/movies.csv") # 构建对应图表 chart = alt.Chart(df).mark_bar(tooltip=None).encode( column=alt.Column("Content Rating:O"), x=alt.X( "Creative Type:N", scale=alt.Scale(rangeStep=15), axis=alt.Axis(title="", labels=False, ticks=False) ), y=alt.Y( "mean(Production Budget):Q", axis=alt.Axis(title="AVG (Production Budget)", format="~s") ), color=alt.Color("Creative Type:N") ) chart.show()
3. 使用vega库直接渲染
如果无需依赖Altair,可直接用vega库加载并渲染Vega-Lite规范,兼容性更好:
先安装依赖:
pip install vega
再运行渲染代码:
import vega spec_str= '''{"$schema": "https://vega.github.io/schema/vega-lite/v3.json", "data": {"url": "https://raw.githubusercontent.com/nlvcorpus/nlvcorpus.github.io/main/datasets/movies.csv"}, "mark": {"type": "bar", "tooltip": null}, "encoding": {"column": {"field": "Content Rating", "type": "ordinal"}, "x": {"field": "Creative Type", "scale": {"rangeStep": 15}, "type": "nominal", "axis": {"title": "", "labels": false, "ticks": false}}, "y": {"aggregate": "mean", "field": "Production Budget", "type": "quantitative", "axis": {"title": "AVG (Production Budget)", "format": "~s"}}, "color": {"field": "Creative Type", "type": "nominal"}}}''' vega.render(spec_str)
内容的提问来源于stack exchange,提问作者hutmh
相关产品推荐
相关产品推荐

