使用Select小部件和CustomJS尝试更新Bokeh源时遇到一些麻烦。在这种情况下,CustomJS是强制性要求,因此无法使用def:函数。
下面的代码返回了数据可视化,但是它没有刷新,因为我猜想JS代码编写不正确,而且我也没有办法对其进行调试(如果有人知道如何,请它确实是我能得到的最佳答案)。
主要思想是根据“选择”小部件上选择的值来过滤我的源。
有任何想法吗??
source = ColumnDataSource(data=dict(
x=gx,
y=gy,
recty=recty,
colors=colors,
filter_info= filter_info))
select = Select(title="Option:", value="All", options=["All", "1", "2", "3", "4", "5", "6+"])
renderer_source = source
# Add the slider
code = """
var value_filter_info = cb_obj.value;
if value_assignments == 'All' {
new_source_data['x'] = source.data['x'];
new_source_data['y'] = source.data['y'];
new_source_data['recty'] = source.data['recty'];
new_source_data['colors'] = source.data['colors'];
} else {
new_source_data['x'] = source.data['x'][source.data['filter_info']==value_filter_info];
new_source_data['y'] = source.data['y'][source.data['filter_info']==value_filter_info];
new_source_data['recty'] = source.data['recty'][source.data['filter_info']==value_filter_info];
new_source_data['colors'] = source.data['colors'][source.data['filter_info']==value_filter_info];
}
renderer_source.data= new_source_data;
renderer_source.change.emit();
"""
callback = CustomJS(args=dict(source=source, renderer_source=renderer_source), code=code)
select.js_on_change('value', callback)
p = figure(plot_width=1200, plot_height=400, x_range=(0,100), y_range=(0,1000))
p.rect(x='x', y='recty', width=1, height=1, color='colors', source=renderer_source, line_color=None, fill_alpha=1, width_units="data", height_units="data")
plot_layout = column(select,p)
show(plot_layout)
output_notebook()
非常感谢!
最佳答案
因此,我找到了可以从美学,程序和视觉上改进的解决方案,但至少可以显示出结果。
遵循@bigreddot关于索引和覆盖的建议,我设法编写了当前的CustomJS代码:
code = """
var render=renderer_source.data;
var data=source.data;
var data_assignment = data['assignments'];
var value_assignments = cb_obj.value;
var data_x=data['x'];
var data_y=data['y'];
var data_recty=data['recty'];
var data_colors=data['colors'];
var render_x=render['x'];
var render_y=render['y'];
var render_recty=render['recty'];
var render_colors=render['colors'];
var x = [];
var y = [];
var recty = [];
var colors = [];
render_x=[];
render_y=[];
render_recty=[];
render_colors=[];
for (var i=0;i<data_assignment.length; i++){
if (value_assignments == 'All') {
x.push(data_x[i]);
y.push(data_y[i]);
recty.push(data_recty[i]);
colors.push(data_colors[i]);
} else if (data_assignment[i]==value_assignments) {
x.push(data_x[i]);
y.push(data_y[i]);
recty.push(data_recty[i]);
colors.push(data_colors[i]);
}
}
renderer_source.data['x']=x;
renderer_source.data['y']=y;
renderer_source.data['recty']=recty;
renderer_source.data['colors']=colors;
renderer_source.change.emit();
"""
关于javascript - 如何使用CustomJS更新Bokeh源,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60289829/