带有pandas数据框的滑块小部件

时间:2019-07-23 06:44:35

标签: python bokeh

我想使用滑块小部件制作交互式散景图。我有一个具有简单值的数据框,并希望使用滑块控件过滤掉一些值。

下面是我的测试代码。

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))

所以,如果代码完成,我可以过滤出一些圆圈,如下图所示

enter image description here

如果有人有个好主意,请给我您出色的代码。谢谢

1 个答案:

答案 0 :(得分:0)

您可以通过遍历原始数据(由原始数据帧制成的字典)并检查圆的阈值是否小于或等于滑块阈值来过滤数据。

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))