slider widget with pandas dataframe

亡梦爱人 提交于 2019-12-14 04:26:49

问题


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.

below is my test code..

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


回答1:


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


来源:https://stackoverflow.com/questions/57158139/slider-widget-with-pandas-dataframe

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