Bokeh结合NetworkX绘制的网络图滑块值下调时更新异常问题求助
问题根因
from_networkx生成的边渲染器数据源中,除Weight/start/end之外,还包含xs/ys等渲染必需的内置字段。你在回调中仅替换了3个自定义字段,其他字段长度仍停留在上次修改后的状态,当滑块下调、需要显示更多边时,不同字段的数组长度不一致,就会触发Shape Mismatch报错。
修复方案
修改CustomJS回调逻辑,遍历备份数据的所有字段统一筛选,保证所有字段长度一致,修正后的完整代码如下:
import pandas as pd import networkx as nx from bokeh.io import show from bokeh.plotting import figure, from_networkx from bokeh.models import CustomJS, Slider from bokeh.layouts import row, column import copy df = pd.DataFrame(data={'Source': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B', 5: 'C'}, 'Target': {0: 'B', 1: 'C', 2: 'D', 3: 'C', 4: 'D', 5: 'D'}, 'Weight': {0: 0, 1: 1, 2: 1.5, 3: 0.6, 4: 3, 5: 4}}) G = nx.from_pandas_edgelist(df, 'Source', 'Target', 'Weight') plot = figure(title='Attempt') network_graph = from_networkx(G, nx.circular_layout, scale=1, center=(0, 0)) plot.renderers.append(network_graph) # 保存完整边数据用于后续筛选 backup_edge_data = copy.deepcopy(network_graph.edge_renderer.data_source.data) slider = Slider(start=0, end=4, value=0, step=.2) code = """ const threshold = cb_obj.value; // 筛选符合条件的索引 const acceptableIndexes = edata["Weight"].reduce((acc, curr, index) => { if (curr >= threshold) acc.push(index); return acc; }, []); // 遍历所有字段统一筛选,保证长度一致 const new_data_edge = {}; Object.keys(edata).forEach(key => { new_data_edge[key] = acceptableIndexes.map(i => edata[key][i]); }); // 替换数据源 graph_setup.edge_renderer.data_source.data = new_data_edge; """ callback = CustomJS(args = dict(graph_setup = network_graph, edata = backup_edge_data), code = code) slider.js_on_change('value', callback) layout = row( plot, column(slider), ) show(layout)
内容的提问来源于stack exchange,提问作者GuglielmoSanchini
相关产品推荐
相关产品推荐

