首页 > 解决方案 > 如何将 Bokeh Tap 事件中的坐标附加到 python 对象?

问题描述

在下面的示例中,当散景图被点击以附加到各自列表中的数据字典 coordList 时,我试图获取出现在图旁边的 Div 中的 x 和 y 坐标。

import numpy as np
from bokeh.io import show, output_notebook
from bokeh.plotting import figure
from bokeh.models import CustomJS, Div
from bokeh.layouts import column, row
from bokeh.events import Tap

coordList = dict(x=[], y=[])

output_notebook()

def display_event(div, attributes=[], style = 'float:left;clear:left;font_size=10pt'):
    "Build a suitable CustomJS to display the current event in the div model."
    return CustomJS(args=dict(div=div), code="""
        var attrs = %s; var args = [];
        for (var i = 0; i<attrs.length; i++) {
            args.push(Number(cb_obj[attrs[i]]).toFixed(2));
        }
        var line = "<span style=%r>(" + args.join(", ") + ")</span>\\n";
        var text = div.text.concat(line);
        var lines = text.split("\\n")
        if (lines.length > 35)
            lines.shift();
        div.text = lines.join("\\n");
    """ % (attributes, style))

x = np.random.random(size=4000) * 100
y = np.random.random(size=4000) * 100
radii = np.random.random(size=4000) * 1.5
colors = ["#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y)]

p = figure(tools="pan,wheel_zoom,zoom_in,zoom_out,reset")
p.scatter(x, y, radius=np.random.random(size=4000) * 1.5,
          fill_color=colors, fill_alpha=0.6, line_color=None)

div = Div(width=400, height=p.plot_height)
layout = row(p, div)

point_attributes = ['x', 'y']

p.js_on_event(Tap, display_event(div, attributes=point_attributes))

show(layout)

我不确定如何保存坐标以及如何访问它们并将它们附加到列表中。

标签: pythonbokeh

解决方案


无法使用上述代码将坐标附加到 python 对象,因为该代码正在生成独立输出(即,它正在使用“show”)。独立输出是发送到浏览器的纯静态 HTML 和 Bokeh JSON,与任何 Python 进程没有任何形式的连接。如果您想将 Bokeh 可视化连接到真正运行的 Python 进程,这就是 Bokeh 服务器的用途

如果您运行 Bokeh 服务器应用程序,那么您可以使用on_event真正的 python 回调来使用 Tap 偶数值运行您想要的任何 python 代码:

def callback(event):
    # use event['x'], event['y'], event['sx'], event['sy']

p.on_event(Tap, callback)

推荐阅读