htmlhidebokehmutevline

How to Hide Span Lines in Bokeh


I have a bokeh plot with a scatter and a line plot and many span vlines. The line plot can easily be hidden via the legend, but how do I hide span lines? I want to click on individual span lines to either mute or hide them completely. How can this be done?


Solution

  • The solution I want to show is an adaption from here where checkboxes are used to toggle lines. This can be done for Spans as well.

    from bokeh.io import output_notebook, show
    from bokeh.models import Span, CheckboxGroup, CustomJS
    from bokeh.plotting import figure
    from bokeh.layouts import row
    output_notebook()
    
    p = figure(width=300, height=300)
    p.line(x=[1,2,3,4,5], y=[1,2,3,4,5], line_width=2, legend_label='Line')
    s = []
    span_positions = [2.5,3.5]
    for pos in span_positions:
        s.append(Span(dimension='height', location=pos))
    p.renderers.extend(s)
    
    checkbox = CheckboxGroup(
        labels=['Span_'+str(i) for i in span_positions], 
        active=list(range(len(span_positions))), 
        width=100
    )
    callback = CustomJS(args=dict(spans=s,checkbox=checkbox),
        code="""
        for(var i=0; i<spans.length; i++){
            spans[i].visible = checkbox.active.includes(i);
        }
        """
    )
    checkbox.js_on_change('active', callback)
    layout = row(p,checkbox)
    show(layout)
    

    Output

    toggle spans

    Comment

    I tried to add Spans to the legend to avoid CheckBoxes, but I was not able to, because LegendItem from bokeh does not accept Spans. So this might not be ideal.