Search code examples
bokeh

How to show or hide a graph line in Bokeh


How do we toggle a line on and off (hide or show) in Bokeh again ? The example figure below does not update.

from bokeh.io import output_file, show
from bokeh.layouts import row
from bokeh.plotting import figure
from bokeh.models import CheckboxGroup, CustomJS

output_file("toggle_lines.html")

### Main plot
plot = figure()

# Dummy data for testing
x = list(range(25))
y0 = [ 3**a for a in x]

l0 = plot.line(x, y0, color='blue')
l0.visible = False

checkbox = CheckboxGroup(labels=["l0"], active=[1])

checkbox.js_on_click(CustomJS(args=dict(l0=l0), code="""l0.visible = 0 in checkbox.active;"""))

layout = row(checkbox, plot)
show(layout)

Thank you,


Solution

  • Two main things:

    1. your active argument should either be [0] indicating that the 0th checkbutton in the Group should be active, or should not be supplied, indicating that the default state of all checkboxes should be inactive. By indicating [1] you're telling bokeh there's actually 2 checkboxes and 1 of them is active which leads to errors.
    2. You'll need to pass your checkbox object into the javascript code via the args in your callback (you've already done this with the line, just need to include the checkbox group as well.

    This code worked for me:

    from bokeh.io import output_file, show
    from bokeh.layouts import row
    from bokeh.plotting import figure
    from bokeh.models import CheckboxGroup, CustomJS
    
    output_file("toggle_lines.html")
    
    ### Main plot
    plot = figure(x_range=(0, 25))
    
    # Dummy data for testing
    x = list(range(25))
    y0 = [ 3**a for a in x]
    
    l0 = plot.line(x, y0, color='blue')
    l0.visible = False
    
    checkbox = CheckboxGroup(labels=["l0"])
    
    checkbox.js_on_click(CustomJS(args=dict(l0=l0, checkbox=checkbox), code="""l0.visible = 0 in checkbox.active;"""))
    
    layout = row(checkbox, plot)
    show(layout)