Here is code which works with Bokeh 2.4.3:
from bokeh.layouts import column
from bokeh.models import Legend, LegendItem
from bokeh.plotting import figure, curdoc
from bokeh.sampledata.autompg import autompg
from bokeh.transform import jitter
years = sorted(autompg.yr.unique())
# Some example graphs from example on web
p1 = figure(width=600, height=300, title="Years vs mpg without jittering")
p1.xgrid.grid_line_color = None
p1.xaxis.ticker = years
p1.scatter(x='yr', y='mpg', size=9, alpha=0.4, source=autompg)
p2 = figure(width=600, height=300, title="Years vs mpg with jittering")
p2.xgrid.grid_line_color = None
p2.xaxis.ticker = years
scatter = p2.scatter(x=jitter('yr', 0.4), y='mpg', size=9, alpha=0.4, source=autompg)
# Add a legend
legend_items = []
legend_items.append(LegendItem(label='line X', renderers=[scatter]))
legend = Legend(items=legend_items)
p2.add_layout(legend,place='right')
# Add a label to the legend
p2.legend.items.insert(0, LegendItem(label="label", tags=['legend_label']))
# Add a callback which changes the label on the legend
def _on_x_range_end_changed(attr, old, new):
print("change:", attr, old, new)
p2.legend.items[0].label['value'] = f"{attr} {old}->{new}"
p1.x_range.on_change('end', _on_x_range_end_changed)
# add column - need to run this with bokeh --serve
curdoc().add_root(column(p1, p2))
However this doesn’t work with Bokeh 3.6.0. Get “TypeError: ‘Value’ object does not support item assignment”.
Would expect this to work:
p2.legend.items[0].label.value = f"{attr} {old}->{new}"
but though I think the value is being updated the legend doesn’t update.