Updating legend label using callback

You will have to construct the legend yourself:

from random import random

from bokeh.io import show
from bokeh.layouts import row, column
from bokeh.models import Select, ColumnDataSource, CustomJS, Legend, LegendItem
from bokeh.plotting import figure

ds = ColumnDataSource(dict(x_coord=list(range(10)),
                           **{l: [random() for _ in range(10)] for l in 'abcxyz'}))
f = figure(x_axis_label='coord', y_axis_label='value')


def add_line(options, init, color):
    s = Select(options=options, value=init)
    r = f.line(x='x_coord', y=init, source=ds, line_width=3, line_color=color)
    li = LegendItem(label=init, renderers=[r])
    s.js_on_change('value', CustomJS(args=dict(r=r, li=li),
                                     code="""
                                         r.glyph.y = {field: cb_obj.value};
                                         li.label = {value: cb_obj.value};
                                     """))
    return s, li


s1, li1 = add_line(list('abc'), 'a', 'green')
s2, li2 = add_line(list('xyz'), 'z', 'red')
f.add_layout(Legend(items=[li1, li2]))

show(row(column(s1, s2), f))

Note that my particular example doesn’t even need a server - everything happens on the frontend.

1 Like