以下是使用Bokeh库实现根据选定的点改变平均值的代码示例:
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.layouts import row
from bokeh.io import output_notebook
# 创建数据源
data = {'x': [1, 2, 3, 4, 5], 'y': [6, 7, 8, 9, 10]}
source = ColumnDataSource(data=data)
# 创建绘图工具
p = figure(plot_width=400, plot_height=400)
p.circle('x', 'y', size=10, source=source)
# 创建JavaScript回调函数
callback = CustomJS(args={'source': source}, code="""
// 获取选定的数据点的索引
const selected = source.selected.indices;
// 如果没有选定的点,直接返回
if (selected.length === 0)
return;
// 计算选定的点的平均值
let sum = 0;
for (let i = 0; i < selected.length; i++) {
sum += source.data.y[selected[i]];
}
const avg = sum / selected.length;
// 将平均值更新到数据源中
for (let i = 0; i < selected.length; i++) {
source.data.y[selected[i]] = avg;
}
// 更新数据源
source.change.emit();
""")
# 将回调函数绑定到数据源的选定事件上
source.selected.js_on_change('indices', callback)
# 在notebook中显示图形
output_notebook()
show(row(p))
这个例子创建了一个散点图,当用户选择一个或多个点时,通过JavaScript回调函数计算选定点的平均值,并将这个平均值更新到数据源中。随后,数据源的变化将触发图形的更新,从而更新散点图中选定点的y值为平均值。
上一篇:Bokeh - 更新滑动条函数