pythonbokehholoviews

Using a checkbox widget in Holoviews to toggle visibility of Point plot


I have the following code which gives me a scatter plot of two groups of points:

import pandas as pd
import holoviews as hv

hv.extension('bokeh')

df1 = pd.DataFrame(data = {'x':range(1,5), 'y':range(1,5)})
df2 = pd.DataFrame(data = {'x':range(5,10), 'y':range(5,10)})
    
p1 = hv.Points(df1, label = 'a').opts(marker = 's')
p2 = hv.Points(df2, label = 'b').opts(marker = 'o')
options = hv.opts.Points(size = 10, show_legend = True)
                          
(p1*p2).opts(options)

I want to add checkboxes to toggle the visibility of the point groups. I know I can add the checkboxes like this:

a_checkbox = pn.widgets.Checkbox(name='a', value=True)
b_checkbox = pn.widgets.Checkbox(name='b', value=True)       
                          
pn.Column(a_checkbox, b_checkbox, ((p1*p2).opts(options)))

But I'm note sure how to make them interactive. Can anyone help with this?

Thanks!


Solution

  • The legend already works like that (try it!), but if you want a separate checkbox, here's one way that works whenever a widget value maps directly to an option setting:

    import pandas as pd, panel as pn, holoviews as hv
    hv.extension('bokeh')
    
    df1 = pd.DataFrame(data = {'x':range(1,5),  'y':range(1,5)})
    df2 = pd.DataFrame(data = {'x':range(5,10), 'y':range(5,10)})
        
    a_checkbox = pn.widgets.Checkbox(name='a', value=True)
    b_checkbox = pn.widgets.Checkbox(name='b', value=True)       
    
    p1 = hv.Points(df1, label = 'a').opts(marker = 's').apply.opts(alpha=a_checkbox)
    p2 = hv.Points(df2, label = 'b').opts(marker = 'o').apply.opts(alpha=b_checkbox)
    options = hv.opts.Points(size = 10, show_legend = True)
                              
    (p1*p2).opts(options)
                              
    pn.Column(a_checkbox, b_checkbox, ((p1*p2).opts(options)))
    

    screenshot