You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用BokehJS自动生成三个折线图的求和折线图?

BokehJS实现多折线Y值求和的动态折线图

完全可以实现你的需求,而且通过BokehJS的JS回调就能轻松完成——动态计算三个折线图的Y值之和,自动生成第四个汇总折线图。

实现步骤与代码示例

1. 准备数据源

先创建三个原始折线的数据源,以及用于汇总折线的空数据源:

// 原始数据
const x = [0, 1, 2, 3, 4];
const y1 = [1, 2, 3, 4, 5];
const y2 = [4, 5, 6, 7, 8];
const y3 = [1, 8, 2, 6, 4];

// 初始化数据源
const source1 = new Bokeh.ColumnDataSource({ data: { x, y: y1 } });
const source2 = new Bokeh.ColumnDataSource({ data: { x, y: y2 } });
const source3 = new Bokeh.ColumnDataSource({ data: { x, y: y3 } });
const sourceAll = new Bokeh.ColumnDataSource({ data: { x, y: [] } });

2. 编写求和回调函数

定义一个函数,负责计算三个Y数组对应位置的和,并更新汇总数据源:

function updateTotal() {
    const yArr1 = source1.data.y;
    const yArr2 = source2.data.y;
    const yArr3 = source3.data.y;
    
    // 按索引逐位求和
    const yTotal = yArr1.map((val, idx) => val + yArr2[idx] + yArr3[idx]);
    
    // 更新汇总数据源并通知Bokeh刷新
    sourceAll.data = { x: x, y: yTotal };
    sourceAll.change.emit();
}

3. 绑定数据更新监听

给三个原始数据源绑定change事件,只要它们的数据发生变化,就自动触发求和:

source1.on('change', updateTotal);
source2.on('change', updateTotal);
source3.on('change', updateTotal);

4. 初始化与渲染图表

页面加载时先计算一次初始总和,然后创建并渲染所有折线图:

// 初始化时生成初始汇总数据
updateTotal();

// 创建画布
const plot = new Bokeh.Figure({
    title: '折线Y值求和示例',
    x_axis_label: 'X轴',
    y_axis_label: 'Y轴',
    width: 800,
    height: 450
});

// 添加原始折线
plot.line({ field: 'x' }, { field: 'y' }, { source: source1, color: '#ff4444', legend_label: 'Y1' });
plot.line({ field: 'x' }, { field: 'y' }, { source: source2, color: '#33b5e5', legend_label: 'Y2' });
plot.line({ field: 'x' }, { field: 'y' }, { source: source3, color: '#99cc00', legend_label: 'Y3' });

// 添加汇总折线
plot.line({ field: 'x' }, { field: 'y' }, { source: sourceAll, color: '#000000', line_width: 2, legend_label: 'Y总和' });

// 渲染到页面指定容器
Bokeh.embed.add_document(plot, document.getElementById('chart-container'));

注意事项

  • 确保三个原始折线的X轴数据长度一致,否则求和时会出现索引越界问题。
  • 如果需要支持动态修改原始数据(比如通过控件调整),只要更新对应ColumnDataSource的data属性,回调会自动触发并更新汇总折线。

内容的提问来源于stack exchange,提问作者mojovski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 07:57:15