如何从ColumnDataSource对象获取数据,该对象与Bokeh的CustomJS函数的局部变量同步?

时间:2016-02-27 12:14:42

标签: python callback bokeh

基于以下代码示例,我想在CustomJS函数中提取数据(例如x值),以将其保存在python列表rect_data中。虽然变量x与ColumnDataSource对象source同步,但是当我在下面执行的代码的图中绘制矩形选择时,python列表rect_data仍然是一个空列表。我做错了什么,我该如何解决这个问题?

提前谢谢!

# You must first run "bokeh serve" to view this example

from bokeh.models import CustomJS, ColumnDataSource, BoxSelectTool, Range1d, Rect
from bokeh.plotting import figure, show
from bokeh.client import push_session
from bokeh.io import curdoc

source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))

callback = CustomJS(args=dict(source=source), code="""

        var data = source.get('data');
        var geometry = cb_data['geometry'];


        var width = geometry['x1'] - geometry['x0'];
        var height = geometry['y1'] - geometry['y0'];
        var x = geometry['x0'] + width/2;
        var y = geometry['y0'] + height/2;


        data['x'].push(x);
        data['y'].push(y);
        data['width'].push(width);
        data['height'].push(height);


        source.trigger('change');
    """)

box_select = BoxSelectTool(callback=callback)

p = figure(plot_width=400,
           plot_height=400,
           tools=[box_select],
           title="Select Below",
           x_range=Range1d(start=0.0, end=1.0),
           y_range=Range1d(start=0.0, end=1.0))


rect = Rect(x='x',
            y='y',
            width='width',
            height='height',
            fill_alpha=0.3,
            fill_color='#009933')



p.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect)

session = push_session(curdoc())

def update():
    global rect_data
    global source    
    rect_data = source.data['x']
    print(rect_data)


curdoc().add_periodic_callback(update,10)
session.show() 
session.loop_until_closed() 

1 个答案:

答案 0 :(得分:2)

您可以将ToolEvents用于此目的。见下面的例子。

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include 'dbconfic.inc.php';

if(isset($_POST['createWebshopInput']) && $_POST['createWebshopInput'] != '')
    {
        $response = array();
        $shop = mysqli_real_escape_string($mysqli,$_POST['createWebshopInput']);
        $sql  = "SELECT name FROM webshops";
        $res    = mysqli_query($mysqli, $sql);
        $count  = mysqli_num_rows($res);
        if($count > 0)
        {
            $response['status'] = false;
            $response['msg'] = 'Webshop Already Exist.';
        }
        else
        {
            $response['status'] = true;
            $response['msg'] = 'Webshop available.';
        }
         echo json_encode($response);
    }?>

至少在Bokeh 0.11.1中,没有事件发送回Python的ColumnDataSource。