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)
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.
The changes I made are
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
I also tried using
source = ColumnDataSource(data = dict( ... ) ...
callback = CustomJS(args=dict(source=source), code="""
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 !! :)