选择下拉选项后,如何在绘图上“ change.emit”或“ trigger change”?

时间:2019-05-10 09:18:41

标签: bokeh bokehjs

任何想法都应该在三重'?'处去吗?

import pandas as pd
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, Slider, Select
import bokeh.plotting as bp
from bokeh.plotting import Figure, output_file, show
from bokeh.models import HoverTool, DatetimeTickFormatter

# Create an output file
bp.output_file('columnDataSource.html')

# Create your plot as a bokeh.figure object
myPlot = bp.figure(height = 600,
               width = 800,
               y_range=(0,3))

x_values = [1, 2, 3, 4, 5]
y_values = [1, 2, 3, 4, 5]

myPlot.line(x = x_values, y= y_values, line_width=2)

callback = CustomJS(args={
    'source1': {'x': [1,2,3,4], 'y':[1,1,1,1]},
    'source2': {'x': [0,0,0,0], 'y':[2,2,2,2]},
    'source3': {'x': [1,2,3,4], 'y':[1,1,1,1]}}, 

    code="""

    var data1 = source1;
    var data2 = source2;
    var data3 = source3;

    var f = cb_obj.value;

    if(f == 'A'){
    console.log("A selected from dropdown.");
    data1.x = data1.x;
    data1.y = data1.y;
    }

    else if(f == 'B'){
    // Substitute all old data1 values in with data2 values
    console.log("B selected from dropdown.");
    data1.x = data2.x;
    data1.y = data2.y;
    }

    else{
    console.log("C selected.");
    // Substitute all old data1 values in with data3 values
    data1.x = data3.x;
    data1.y = data3.y;
    }

    // Problematic line!
    ???.change.emit();
""")


select = Select(title='Choose', value='A', options=['A','B','C'])
select.js_on_change('value', callback)

layout = column(select, myPlot)

show(layout) # et voilà.

我希望我的x和y值发生变化,并相应地绘制到我的散景图上。

由于我不知道应该调用哪个对象的“触发”功能,因此目前没有任何变化。请帮助,我是Bokeh的新手。

1 个答案:

答案 0 :(得分:0)

如果您通过引用更新了数据源字段,则您进行ColumnDataSource.change.emit()。当您仅更新x或仅更新y时:

ColumnDataSource.data['x'] = [4, 3, 2, 1]
ColumnDataSource.change.emit()

同时更新它们都可以:

ColumnDataSource.data = new_data

new_data{'x': [1], 'y':[2]}之类的新json对象。 原因是当将现有对象替换为新对象时,JS可以自动检测到更改,但是无法通过引用检测到更改,因此在这种情况下,您需要显式调用:ColumnDataSource.change.emit()以更新BokehJS模型。 / p>

这是您修改的代码:

from bokeh.models import CustomJS, ColumnDataSource, Select, Column
from bokeh.plotting import figure, show

myPlot = figure(y_range = (0, 4))

data =  {'A': {'x': [1, 2, 3, 4], 'y':[1, 1, 1, 1]},
         'B': {'x': [1, 2, 3, 4], 'y':[2, 2, 2, 2]},
         'C': {'x': [1, 2, 3, 4], 'y':[3, 3, 3, 3]} }

source = ColumnDataSource(data['A'])
myPlot.line('x', 'y', line_width = 2, source = source)

callback = CustomJS(args = {'source': source, 'data': data},
code = """source.data = data[cb_obj.value]; """)

select = Select(title = 'Choose', value = 'A', options = ['A', 'B', 'C'])
select.js_on_change('value', callback)

layout = Column(select, myPlot)
show(layout)