问题描述
简短版本:带有JS回调的bokeh复选框可绘制数据帧的子集?
Short version: bokeh checkboxes with JS callbacks to plot subsets of a dataframe?
较长版本::答案很好地说明了多选功能,但我想对复选框做同样的事情.我所有的数据都在一个熊猫数据框中,并且我正在使用复选框选择该数据框中的某些位进行绘图.我相信使用复选框与cb_obj.active
有关,但是我不确定如何使它工作.特别是我的绘图包括彩色矩形和文本,其所有信息(位置,文本,颜色)均取自我的数据框.而且我不知道必须在回调中完成多少绘制,以及在外部进行多少绘制.
Longer version: The answer here gives a good explanation for multiselect, but I want to do the same thing for checkboxes. All my data is in one pandas dataframe, and I'm using the checkboxes to select bits of that dataframe for plotting. I believe that with checkboxes it is something to do with cb_obj.active
but I'm very unsure how to get it to work. In particular my plot includes colored rectangles and text, all information for which: position, text, color, is taken from my dataframe. And I don't know how much plotting must be done in the callback, and how much outside.
据我所知,回调函数会调用一个函数来进行实际绘制.
As far as I can tell, the callback calls a function to do the actual plotting.
我知道我应该举一个最小的例子,但是我想不出如何简化我的代码...所以目前,我真正想要的只是一个使用带有JavaScript回调的复选框的示例.绘制数据框的子集.一定有人这样做了,但是我还没有找到一个例子!谢谢.
I know I should give a minimal example, but I can't think how to simplify my code enough... so all I really want at the moment is an example of the use of checkboxes, with a JavaScript callback, to plot a subset of a dataframe. Somebody must have done this, but I haven't found an example yet! Thanks.
推荐答案
以下是示例:
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import Slider, CheckboxGroup, CustomJS, ColumnDataSource, CDSView
from bokeh.models.filters import CustomJSFilter
from bokeh.layouts import row
from bokeh.transform import factor_cmap
from bokeh.palettes import Category10_10
output_notebook()
您可以使用CustomJSFilter
计算要显示的行的索引:
You can use CustomJSFilter
to calculate the indice of rows to show:
from bokeh.sampledata import iris
source = ColumnDataSource(data=iris.flowers)
species = iris.flowers.species.unique().tolist()
checkboxes = CheckboxGroup(labels=species, active=list(range(len(species))))
fig = figure()
filter = CustomJSFilter(code="""
let selected = checkboxes.active.map(i=>checkboxes.labels[i]);
let indices = [];
let column = source.data.species;
for(let i=0; i<column.length; i++){
if(selected.includes(column[i])){
indices.push(i);
}
}
return indices;
""", args=dict(checkboxes=checkboxes, source=source))
checkboxes.js_on_change("active", CustomJS(code="source.change.emit();", args=dict(source=source)))
fig.scatter("sepal_length", "sepal_width",
color=factor_cmap("species", Category10_10, species),
source=source, view=CDSView(source=source, filters=[filter]))
show(row(checkboxes, fig))
这篇关于为bokeh中的复选框实现JavaScript回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!