Search code examples
javascriptpythonbokeh

bokeh trigger js_on_change for first display of graph


I am plotting a bokeh graph ftom a pandas datasource in my website. The pandas dataframe df looks like this:

X   Y   Type
0   5    A
0   15   B
1   12   A
1   18   B

I add a Select object with values A and B. Basically, the user selects the value A or B in that select object, and my CustomJS callback filters the DataSource and plots the graph corrresponding to the selected type:

source = ColumnDataSource(df)
select = Select(title="Select Type:", options=['A', 'B'])
callback = CustomJS(args={'source':source}, code = """
    var t = cb_obj.value
    var a = df.filter(function(c){if (c['Type'] == t) return c;});
    source.data['X'] = []
    source.data['Y'] = []
    for (var i=0; i < a.length; i++) {
      source.data['X'].push(a[i]['%s']);
      source.data['Y'].push(a[i]['Y']);
    }
    source.change.emit();
  """
select.value = 'A'

The problem is that the graph looks messy when it is first displayed. Indeed it plots all the X and Y columns, and I have to manually change the default selected type in the dropdown to get the callback triggered and the data correctly filtered.

Can I smehow trigger that callback programmatically before first display of my graph?


Solution

  • There is no way to trigger the callback up front. Instead, you should make sure (in Python) that the CDS is initialized to the correct initial state that you actually want to be displayed.

    However, if what you are trying to do is select between subsets of the data then the approach you have above cannot work. You are actually updating the only data source you have, with will throw away data on every callback (that you cannot get back). Instead you should use the select callback to configure a Bokeh filter:

    https://docs.bokeh.org/en/latest/docs/user_guide/data.html#filtering-data

    Specifically you probably want a GroupFilter and there is some example/discussion on the Discourse:

    https://discourse.bokeh.org/t/scatter-plot-legend-doesnt-update-correctly-when-data-is-updated/5545