以下是一个示例代码,演示了如何使用Bokeh的CustomJS来传递图元数组:
from bokeh.plotting import figure, show
from bokeh.models import CustomJS, ColumnDataSource
# 创建一个图表
p = figure(plot_width=400, plot_height=400)
# 创建图元数组
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 4, 5]
# 创建数据源
source = ColumnDataSource(data=dict(x=x, y=y))
# 在图上绘制图元
p.circle('x', 'y', source=source, size=20)
# 创建一个CustomJS回调函数,用于修改图元数组
callback = CustomJS(args=dict(source=source), code="""
// 获取图元数组
const data = source.data;
// 修改图元数组
data['x'] = [2, 4, 6, 8, 10];
data['y'] = [1, 3, 5, 7, 9];
// 更新数据源
source.change.emit();
""")
# 将回调函数绑定到一个按钮上
button = Button(label="Update Data")
button.js_on_click(callback)
# 显示图表和按钮
show(column(p, button))
在这个示例中,我们首先创建了一个图表并绘制了一个图元数组。然后,我们创建了一个数据源来存储图元数组的数据。接下来,我们创建了一个CustomJS回调函数,用于修改图元数组的值,并通过数据源的change.emit()
方法来更新数据源。最后,我们将回调函数绑定到一个按钮上,并使用show()
方法显示图表和按钮。当按钮被点击时,回调函数将被执行,图元数组的值将被修改并更新到图表上。