使用散景中的复选框小部件隐藏或显示动态行数的行 [英] Using checkbox widget in Bokeh to hide or show lines for dynamic number of lines

查看:53
本文介绍了使用散景中的复选框小部件隐藏或显示动态行数的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在bokeh情节中添加复选框,以便可以隐藏或显示情节中的不同线条.我从github找到了一些代码,并对其进行了修改以实现我的目的.请看下面的代码,

I am trying to add checkboxes in my bokeh plot so that I can hide or show different lines in my plot. I found some code from github and modified it to fulfil my purpose. Please have a look into the below code,

    for data, name, color in zip([AAPL, IBM, MSFT, GOOG], ["AAPL", "IBM", "MSFT", "GOOG"], Spectral4):          
        df = pd.DataFrame(data) 
        source = ColumnDataSource(data = dict(date = pd.to_datetime(df['date']), close = df['close']))                      
        plt = fig.line('date', 'close', line_width=2, color=color, alpha=0.8,
               muted_color=color, muted_alpha=0.2, legend = name, source=source)

        graph_labels.append(name)
        plots.append(plt)

    checkbox = CheckboxGroup(labels = graph_labels, active = [0,1,2,3]) 

    checkbox.callback = CustomJS(args = dict(line0 = plots[0], line1=plots[1], line2=plots[2], line3=plots[3]),  code=""" 
        //console.log(cb_obj.active);
        line0.visible = false;
        line1.visible = false;
        line2.visible = false;
        line3.visible = false;

        for (i in cb_obj.active) {
            //console.log(cb_obj.active[i]);
            if (cb_obj.active[i] == 0) {
                line0.visible = true;
            } else if (cb_obj.active[i] == 1) {
                line1.visible = true;
            } else if (cb_obj.active[i] == 2) {
                line2.visible = true;
            } else if (cb_obj.active[i] == 3) {
                line3.visible = true;
            }
        }
    """)

    layout = row(fig, widgetbox(checkbox), sizing_mode='fixed')

    show(layout)     

此代码可以完美运行.但是我的要求是其他.就我而言,由于我的数据不同,所以每次运行代码时,plt的数量都会有所不同.因此,我尝试修改此代码,但尚未成功.

This code works perfectly. However my requirment is something else. In my case the number of plts will be different each time I run the code as my data is different. So I tried to modify this code but have not had any success yet.

我所做的更改是

    checkbox = CheckboxGroup(labels = graph_labels, active = list(range(0, len(plots))))
    arg_list = []

    for idx in range(0, len(plots)):
        arg_list.append('line' + str(idx))
        arg_list.append(plots[idx])

    i = iter(arg_list)  
    checkbox.callback = CustomJS(args = dict(izip(i, i)),  code=""" 
        // Here I don't know how to use dynamic names for line0 and line1 and use them to control their visibility
        // As type of line0 is object and if I 'm trying to make a dynamic string I can't convert it to object and it fails

我也尝试使用

    source = ColumnDataSource(data = dict( ... ) ...
    callback = CustomJS(args=dict(source=source), code="""

但是它也失败了,没有显示任何情节.我正在使用最新版本的Bokeh和python 2.7任何建议都高度重视,并在此先感谢!:)

But it failed as well and did not show any plot. I'm using the latest version of Bokeh and python 2.7 Any suggestion is highly appriciated and thanks in advance !! :)

推荐答案

您可以执行以下操作:

from bokeh.io import show
from bokeh.plotting import figure
from bokeh.models import CustomJS, CheckboxGroup
from bokeh.layouts import Row
from bokeh.palettes import Category20_20

from random import random,choice

N_lines = int(100*random())/10 # undefined but known from the start number of lines.

x= range(3)
fig = figure()
args = []
code = "active = cb_obj.active;"
for i in range(N_lines):
    glyph = fig.line(x,[random() for j in x],color=choice(Category20_20))
    args += [('glyph'+str(i),glyph)]
    code += "glyph{}.visible = active.includes({});".format(i,i)

checkbox = CheckboxGroup(labels=[str(i) for i in range(N_lines)],active=range(N_lines))

checkbox.callback = CustomJS(args={key:value for key,value in args},code=code)

show(Row(fig,checkbox))

这将基于行数构建回调代码.由于您要求使用代码来适应您的数据,因此您当然可以确定数据中的行数.

This builds the callback code based on the number of lines. Since you asked for the code to adapt to your data, you can certainly determine the number of lines from the data.

之后,如果您还想通过交互来动态添加行,则需要更新:

After that, if you also want to add lines dynamically through interactions you need to update:

checkbox.labels (只需添加一个标签名称)

checkbox.labels (just add one label name)

checkbox.active (将其设置为包含一个数字的range()列表)

checkbox.active (set it to a range() list with one more number)

checkbox.callback (其中一对用于"args",另一对用于"code")

checkbox.callback (with one more pair for "args" and one more entry for "code")

这篇关于使用散景中的复选框小部件隐藏或显示动态行数的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆