Altair无需预生成全量配对数据实现关联矩阵联动散点图的方法
可行高效实现方案
完全可以避免提前生成所有pairwise配对的冗余数据集,大幅降低性能开销,核心是利用Altair的表达式语法动态读取选择器返回的condition_x和condition_y值,指定对应列作为x、y轴编码,无需提前做笛卡尔积拼接,具体实现如下:
核心逻辑
- 无需预生成
paired_df,直接基于原始长表df做一步透视,得到每个id对应的各condition的value列,数据量仅等于原始id的数量 - 编码x/y轴时用
alt.expr动态读取选择器选中的条件值,取对应列作为轴数据源,无需提前生成所有配对组合
完整示例代码
import pandas as pd import numpy as np import altair as alt # 原始数据集,无需预生成配对表 df = pd.DataFrame( { 'id': ['w', 'x', 'y', 'z', 'w', 'x', 'y', 'z', 'w', 'x', 'y', 'z'], 'condition': ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c'], 'value': np.arange(12) } ) # 相关系数矩阵,和原有逻辑一致 corr = pd.DataFrame( { 'condition_x': {0: 'a', 1: 'b', 2: 'c', 3: 'a', 4: 'b', 5: 'c', 6: 'a', 7: 'b', 8: 'c'}, 'condition_y': {0: 'a', 1: 'a', 2: 'a', 3: 'b', 4: 'b', 5: 'b', 6: 'c', 7: 'c', 8: 'c'}, 'r^2': {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0, 5: 1.0, 6: 1.0, 7: 1.0, 8: 1.0} } ) # 热图选择器,和原有逻辑一致 selection = alt.selection_single(fields=['condition_x', 'condition_y'], empty='none') heatmap = alt.Chart(corr).mark_rect().encode( x='condition_x', y='condition_y', color='r^2', ).add_selection(selection) # 散点图直接基于原始df处理,无需预生成配对表 scatter = alt.Chart(df).mark_circle().transform_pivot( 'condition', groupby=['id'], value='value' # 核心:动态取选择器对应的列作为x/y轴 ).encode( x=alt.X('x:Q', title='value of selected condition x'), y=alt.Y('y:Q', title='value of selected condition y'), # 用transform_calculate动态计算x、y值,读取选择器的字段值匹配列 ).transform_calculate( x = 'datum[selection.condition_x]', y = 'datum[selection.condition_y]' ) # 组合图表 heatmap | scatter
性能优势
对比原有预生成所有配对表的方案,该方案的数据集大小仅和原始id数量成正比,不会随着condition数量增加出现O(n²)的性能爆炸,完全适配大规模数据集的需求。
内容的提问来源于stack exchange,提问作者aysung
相关产品推荐
相关产品推荐

