Search code examples
pythonbokehpandas-bokeh

Bokeh: Updating of legend when using different views


I have an issue with updating legend_groups in bokeh:

My data is based on four columns: x-values, y-values, categorization, geography. I created a scatterplot in Bokeh with all scatter points coming from the same x- and y-column. I split the scatter points into two categories (0 and 1) based on the categorization column. I then used factor_mark and factor_color to display the two categories with different colors (orange vs blue).

I further used legend_group to create the legend for the scatter plot. That works fine. The legend looks like this:

0 orange 1 blue

Here a code snippet:

renderer_scatter = plot.scatter(
    x='x', y='y', source=data_provider,
    view=data_provider.geography, size=5, fill_alpha=0.4,
    marker=factor_mark('x', ['hex', 'triangle'], 'categorization'),
    color=factor_cmap('x', 'Category10_3', 'categorization'), legend_group='categorization')

I further added a drop-down to my dashboard which specifies the views of my data based on geography.

Unfortunately, the legend_group does not update appropriately when I change the view. Depending on the geography it looks like this:

0 blue 1 blue

or

0 orange 1 orange

or

0 orange 1

and so on.

The scatterplot itself updates perfectly fine.

Do you have any idea what the issue might be? Thanks a lot in advance!


Solution

  • legend_group is a shorthand convenience for computing legend entries once, up front, when the figure is created in Python. If you need something that reacts to data changes dynamically, then you want to use legend_field which is computed on the "JavaScript side" in the browser. (Or alternatively, you can manage LegendItem objects completely manually, adding and removing as the data changes.)