在Bokeh服务器中,"on_change"方法通常用于监测图形中的属性变化。然而,它无法直接从选中的图元中起作用。要解决这个问题,可以通过使用Bokeh的"selected"属性来实现,该属性可以跟踪被选中的图元。下面是一个示例代码:
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource
from bokeh.events import SelectionGeometry
# 创建一个Figure对象和ColumnDataSource对象
p = figure(width=400, height=400, tools="tap")
source = ColumnDataSource(data=dict(x=[1, 2, 3], y=[1, 2, 3]))
# 绘制一个圆形图元
circle = p.circle('x', 'y', source=source, size=20)
# 定义一个回调函数,当图元被选中时触发
def callback(event):
selected_indices = source.selected.indices
if len(selected_indices) > 0:
print("Selected indices:", selected_indices)
# 在这里定义你想要执行的操作
# 将回调函数与图元的tap事件绑定
p.js_on_event(SelectionGeometry, callback)
# 将图形添加到文档中
curdoc().add_root(p)
在上面的示例代码中,我们创建了一个包含三个点的散点图。当用户选择一个或多个散点时,回调函数将被触发,并打印出选中的索引。在回调函数中,你可以根据选中的索引执行任何你想要的操作。