Changing source of plot in bokeh with a callback

懵懂的女人 提交于 2019-12-03 09:13:53

EDIT: obj.trigger('change',arg) was changed for bokeh 0.12.6 and is now deprecated, the new syntax is obj.change.emit(arg), see Bokeh releases

You can empty your "source" data columns and refill them in a for loop with .push()

Also you shouldn't use variable names starting with numbers

codes = """
var f = cb_obj.get('value');
var sdata = source.data;
var data1 = source1.data;
var data2 = source2.data;

if (f == "source1") {
sdata["A"] = [] ;
for (i=0;i<data1["A"].length; i++) {
sdata["A"].push(data1["A"][i]);
}
sdata["B"] = [] ;
for (i=0;i<data1["B"].length; i++) {
sdata["B"].push(data1["B"][i]);
}
source.trigger('change');
};

if (f == "source2") {
sdata["A"] = [] ;
for (i=0;i<data2["A"].length; i++) {
sdata["A"].push(data2["A"][i]);
}
sdata["B"] = [] ;
for (i=0;i<data2["B"].length; i++) {
sdata["B"].push(data2["B"][i]);
}
source.trigger('change');
};
"""

EDIT to answer the comment

from bokeh.plotting import figure, output_file
from bokeh.models import CustomJS, ColumnDataSource, Select
from bokeh.layouts import gridplot
from bokeh.resources import CDN
from bokeh.embed import file_html

from random import random

key_list = list('ABCDEFGHIJKLMNOP')

DATA1 = {key:[random() for i in range(10)] for key in key_list}
DATA2 = {key:[random() for i in range(10)] for key in key_list}
DATA1['xaxis'] = range(10)
DATA2['xaxis'] = range(10)

source1 = ColumnDataSource(data=DATA1)
source2 = ColumnDataSource(data=DATA2)

fill_source = ColumnDataSource(data=DATA1)

fig = figure()

for key in key_list:
    fig.line(x='xaxis',y=key,source=fill_source)

select = Select(options=['source1','source2'],value='source1')

codes = """
var f = cb_obj.value;
var sdata = source.data;
var data1 = source1.data;
var data2 = source2.data;

console.log(data2);

for (key in data1) {console.log(key);}

if (f == "source1") {
for (key in data1) {
    sdata[key] = [];
    for (i=0;i<data1[key].length;i++){
    sdata[key].push(data1[key][i]);
    }
}
} else {
for (key in data2) {
    sdata[key] = [];
    for (i=0;i<data2[key].length;i++){
    sdata[key].push(data2[key][i]);
    }
}
};

source.trigger("change");
"""
select.callback = CustomJS(args=dict(source=fill_source,source1=source1,source2=source2),code=codes)

grid = gridplot([[select],[fig]])

outfile=open('select.html','w')
outfile.write(file_html(grid,CDN,'select'))
outfile.close()

The lines console.log() are not necessary, but you can use it to help yourself with understanding/debugging your callbacks, those are print statement in the browser console (right click -> inspect -> Console )

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!