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

Bokeh技术问题:使用编辑工具时如何获取更新后的数据

嘿,这个问题我刚好折腾过,其实Bokeh的ColumnDataSource本身就和Python数据结构无缝对接,把编辑后的点转成numpy数组超简单的!

完整实现步骤

首先先补全你给出的代码,让它能在Jupyter Notebook里正常运行:

from bokeh.plotting import figure, show, Column
from bokeh.models import DataTable, TableColumn, PointDrawTool, ColumnDataSource
from bokeh.io import output_notebook
import numpy as np

# 初始化Jupyter Notebook的Bokeh输出
output_notebook()

# 创建空的数据源,用来存储绘制的点
source = ColumnDataSource(data=dict(x=[], y=[]))

# 创建绘图画布
p = figure(x_range=(0, 10), y_range=(0, 10), tools=[], title="用PointDrawTool绘制/编辑点")
# 绘制初始的点(一开始是空的)
renderer = p.circle(x='x', y='y', source=source, size=12, color='royalblue', alpha=0.8)

# 添加PointDrawTool,指定要操作的图形渲染器
draw_tool = PointDrawTool(renderers=[renderer], empty_value=0)
p.add_tools(draw_tool)
# 设置默认激活这个工具
p.toolbar.active_tap = draw_tool

# 显示绘图界面
show(p)

方法1:手动提取并转换数据

当你在画布上完成点的绘制、编辑或删除后,只需要直接从source.data里提取x和y列的数据,再用numpy.array()转换就行:

# 从数据源中获取最新的x、y坐标列表
x_coords = source.data['x']
y_coords = source.data['y']

# 转换为numpy数组
x_array = np.array(x_coords)
y_array = np.array(y_coords)

# 查看结果
print("X坐标数组:\n", x_array)
print("\nY坐标数组:\n", y_array)

方法2:实时监听数据变化(自动触发转换)

如果想每次编辑点之后自动获取最新的numpy数组,可以给ColumnDataSource添加一个on_change回调函数,这样数据一更新就会触发转换:

def handle_data_update(attr_name, old_value, new_value):
    # 每次数据源更新时执行这个函数
    x_array = np.array(source.data['x'])
    y_array = np.array(source.data['y'])
    print("\n--- 数据已更新 ---")
    print("最新X坐标数组:\n", x_array)
    print("最新Y坐标数组:\n", y_array)

# 监听数据源的data属性变化
source.on_change('data', handle_data_update)

小提示

  • ColumnDataSource是Bokeh交互功能的核心,所有通过工具做的编辑操作都会实时同步到它的data字典里,所以直接取数据就好,不用额外的同步操作。
  • 在Jupyter Notebook里,你可以在单独的单元格里运行提取数据的代码,或者把回调函数放在绘图代码之前,这样编辑点的时候就能看到实时输出了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:47:55