带有 pandas 数据框的滑块小部件
问题描述:
我想使用滑块小部件制作交互式散景图.我有一个具有简单值的数据框,并希望使用滑块小部件过滤掉一些值.
I want to make a interactive bokeh plot using slider widget. I have a dataframe with simple values and want to filter out some values using the slider widget.
下面是我的测试代码.
df = pd.DataFrame({'x':[11,12,13,14,15],'y':[22,23,24,25,26],'threshold':[1,2,3,4,5]})
source = ColumnDataSource(data=df)
plot = Figure(plot_width=400, plot_height=400)
plot.circle('x', 'y', source=source)
slider = Slider(start=1, end=5, value=1, step=1, title="threshold")
callback = CustomJS(
args=dict(source=source),
code="""
??????
??????
??????
??????
source.change.emit();
"""
)
slider.js_on_change('value', callback)
show(column(slider,plot))
所以,如果代码完成,我可以过滤出一些圆圈,如下图所示
So, if the code is done, I can filter some circles out like below picture
如果有人有个好主意,请给我您出色的代码.谢谢
If someone has good idea, please give me your fantastic code. Thanks
答
您可以通过遍历原始数据(由原始数据帧制成的字典)并检查圆的阈值是否小于或等于来过滤数据滑块阈值.
You can filter the data by looping over the original data (dictionary made from the original dataframe) and checking if the threshold value of a circle is smaller or equal to the slider threshold.
import pandas as pd
from bokeh.models import ColumnDataSource, CustomJS, Slider
from bokeh.plotting import figure, show, ColumnDataSource
from bokeh.layouts import column
df = pd.DataFrame({'x':[11,12,13,14,15],'y':[22,23,24,25,26],'threshold':[1,2,3,4,5]})
data = df.to_dict()
source = ColumnDataSource(data=df)
plot = figure(plot_width=400, plot_height=400)
plot.circle('x', 'y', source=source)
slider = Slider(start=1, end=5, value=1, step=1, title="threshold")
callback = CustomJS(
args=dict(source=source, slider=slider, data=data),
code="""
var index = [];
var x = [];
var y = [];
var thresh = [];
for (var i = 0; i < Object.keys(data.threshold).length; i++) {
if(slider.value <= data.threshold[i]) {
index.push(i);
x.push(data.x[i]);
y.push(data.y[i]);
thresh.push(data.threshold[i]);
}
}
source.data.index = index;
source.data.x = x;
source.data.y = y;
source.data.threshold = thresh;
source.change.emit();
"""
)
slider.js_on_change('value', callback)
show(column(slider,plot))