'Using CDSView in bokehjs api

I would like to give a bokeh visualization to a friend to let him explore data. For simplicity, I intend to give him a .html file: all callbacks must be in JS. But I have not found how to use CDSView in bokehjs api

Here is an example with different -not working- leads:

from bokeh.plotting import figure
from bokeh.io import output_file, save
from bokeh.layouts import row
from bokeh.models import ColumnDataSource, CDSView, GroupFilter
from bokeh.models import CheckboxGroup, CustomJS

template = """
{% block postamble %}
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-api-2.4.2.min.js"></script>
{% endblock %}
"""
output_file(filename="Visu.html", title='Visualisation', mode='cdn')

# get data
source = ColumnDataSource(dict(
    x=[1, 2, 3, 1, 2, 3],
    y=[1, 4, 9, 1, 2, 3],
    category=['square', 'square', 'square', 'lin', 'lin', 'lin']))
view = CDSView(source=source,
               filters=[
                   GroupFilter(column_name='category', group="lin"),
               ])
# plot
plot = figure(title="Comparison")
plot.scatter(x="x", y="y", source=source, view=view)

# code for selection of data in js
labels = ["lin", "square"]
checkbox_group = CheckboxGroup(labels=labels, active=[0])

my_js_code = """
// clear array of glyphs (=remove curves)
plot.renderers.length = 0;

// draw selection
let selected = checkboxes.active.map(i=>checkboxes.labels[i]);
for(let indice in selected) {
    let name = selected[indice];
    
    // create new view
    var my_view = new Bokeh.CDSView({
        source: my_source,
        filters: [new Bokeh.GroupFilter({column_name: 'category', group: name})]
    });
    
    // -- ADDING new curve
    // Does not work : "plot.scatter not a function"
    //plot.scatter({field: "x"}, {field: "y"}, {source:my_source, view: my_view}); 
    
    // Work, but no CDSView
    var new_glyph = new Bokeh.Scatter({
        x: { field: "x" },
        y: { field: "y" },
        view: my_view  // useless
    });
    plot.add_glyph(new_glyph, my_source);                   // no CDSView : draw whole source
    // plot.add_glyph(new_glyph, my_source, my_view);       // no error, but doesn't work : draw whole source
    //plot.add_glyph(new_glyph, my_source, view=my_view);   // ReferenceError: assignment to undeclared variable view
}

// update
plot.change.emit();
"""

checkbox_group.js_on_change("active", CustomJS(code=my_js_code, args=dict(my_source=source, plot=plot, checkboxes=checkbox_group)))

save(row(checkbox_group, plot), "visu.html", template=template)

How could we use CDSView in JS callback ?

Thanks for your suggestions !



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source