Skip to content Skip to sidebar Skip to footer

Checkboxgroup In Bokeh To Plot Additive Plots

I want to use a checkbox group to represent linearly additive sources. The idea is for the user to be able to turn on or turn off multiple sources of different kinds to display a p

Solution 1:

Yes, you can achieve this with the CheckboxGroup - you can use the active attribute of CheckboxGroup to select the correct columns to add to the combined plot. Here is a complete example with the data you provided:

from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.layouts import layout, widgetbox
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import CheckboxGroup
import pandas as pd

output_file('additive_checkbox.html')
names = ['Wave', 'A', 'B', 'C']
rows = [(340, 77, 70, 15),
        (341, 80, 73, 15),
        (342, 83, 76, 16),
        (343, 86, 78, 17)]
data = pd.DataFrame(rows, columns=names)
data['combined'] = None
source = ColumnDataSource(data)
callback = CustomJS(args=dict(source=source), code="""
    const labels = cb_obj.labels;
    const active = cb_obj.active;
    const data = source.data;
    const sourceLen = data.combined.length;
    const combined = Array(sourceLen).fill(undefined);
    if (active.length > 0) {
        const selectedColumns = labels.filter((val, ind) => active.includes(ind));
        for(let i = 0; i < sourceLen; i++) {
            let sum = 0;
            for(col of selectedColumns){
                sum += data[col][i];
            }
            combined[i] = sum;
        }
    }
    data.combined=combined;
    source.change.emit();
""")
checkbox_group = CheckboxGroup(labels=names[1:], active=[], callback=callback)
p = figure(width=400, height=400)
p.line(x='Wave', y='combined', source=source)
show(layout([[widgetbox(checkbox_group)], [p]]))

Post a Comment for "Checkboxgroup In Bokeh To Plot Additive Plots"