Vega-Lite转Altair实现pyLDAvis:动态轴排序及转换错误排查
报错根因
触发Altair.vegalite.v4.schema.channels.ColorValue, validating 'additionalProperties' Additional properties are not allowed ('selection' was unexpected)报错的核心问题不是transform转换错误,而是选择器的跨图层引用写法有误:
- 你直接硬编码了Vega-Lite自动生成的选择器ID
selector046,这个ID每次渲染都会动态变化,硬写会导致选择器作用域匹配异常,配置被错误挂载到不支持selection属性的颜色通道下触发校验失败 - 你定义的
pts选择器没有显式命名,其他图层无法正确识别跨图层的选择器参数
修正后的可运行代码
import altair as alt import pandas as pd import numpy as np data={ 'Term': ['algorithm','learning','learning','algorithm','algorithm','learning'], 'Freq_x': [1330,1353,304.42,296.69,157.59,140.35], 'Total': [1330, 1353,1353.7,1330.47,1330.47,1353.7], 'Category': ['Default', 'Default', 'Topic1', 'Topic1', 'Topic2', 'Topic2'], 'logprob': [30.0, 27.0, -5.116, -5.1418, -5.4112, -5.5271], 'loglift': [30.0, 27.0, 0.0975, 0.0891, -0.1803, -0.3135], 'saliency_ind': [0, 3, 76, 77, 181, 186], 'x': [np.nan,np.nan,-0.0080,-0.0080,-0.0053,-0.0053], 'y': [np.nan,np.nan,-0.0056,-0.0056, 0.0003,0.0003], 'topics': [np.nan, np.nan, 1.0, 1.0, 2.0, 2.0], 'cluster': [np.nan, np.nan, 1.0, 1.0, 1.0, 1.0], 'Freq_y': [np.nan,np.nan,20.39,20.39,14.18,14.18]} df=pd.DataFrame(data) # 给选择器显式命名,方便跨图层引用 pts = alt.selection_single(fields=['Category'], empty='none', name='cat_select') points=alt.Chart().mark_circle(tooltip=True).encode( x='mean(x)', y='mean(y)', size='Freq_y', tooltip=['topics', 'cluster'], detail='Category', color=alt.condition(pts, alt.value('#F28E2B'), alt.value('#4E79A7')) ).add_selection(pts) trans=alt.Chart( ).transform_joinaggregate( max_fx='max(Freq_x)' ).transform_calculate( # 使用显式定义的选择器名称引用 filterCategory="cat_select.Category ? cat_select.Category : []" ).transform_calculate( filtered_Freq_x="indexof(datum.filterCategory,datum['Category']) > -1 ? datum['Freq_x'] : null" ).transform_window( Sorted='rank()', sort=[{'field': "filtered_Freq_x:Q", "order": "descending"}] ) b1=alt.Chart().mark_bar().encode( x='Freq_x', y=alt.Y('Term', sort=alt.SortField("Sorted")), tooltip=['Total'], ) b2=alt.Chart().mark_bar(color='#F28E2B').encode( x='filtered_Freq_x:Q', y=alt.Y('Term', sort=alt.SortField("Sorted")), tooltip=['Total'], ) bars_1=trans+b1 bars_2=trans+b2 alt.hconcat(points,bars_1+bars_2, data=df).resolve_legend( color="independent", size="independent" )
关于transform转换的说明
你目前编写的所有transform逻辑(join聚合、计算字段、窗口排序)都已经正确从Vega-Lite规范转换为Altair写法,不需要做额外调整。
内容的提问来源于stack exchange,提问作者campo
相关产品推荐
相关产品推荐

