Bokeh how to add legend to figure created by multi_line method?

On more recent releases (since 0.12.15, I think) its possible to add legends to multi_line plots. You simple need to add a 'legend' entry to your data source. Here is an example taken from the Google Groups discussion forum:

data = {'xs': [np.arange(5) * 1, np.arange(5) * 2],
        'ys': [np.ones(5) * 3, np.ones(5) * 4],
        'labels': ['one', 'two']}

source = ColumnDataSource(data)

p = figure(width=600, height=300)
p.multi_line(xs='xs', ys='ys', legend='labels', source=source)

Maintainer Note : PR #8218 which will be merged for Bokeh 1.0, allows legends to be created directly for multi line and patches, without any looping.


To make it faster, when you have a lot of data or a big table etc. You can make a for loop:

1) Make a list of colors and legends

You can always import bokeh paletts for your colors
from bokeh.palettes import "your palett"
Check this link: bokeh.palets

colors_list = ['blue', 'yellow']
legends_list = ['first', 'second']
xs=[[4, 2, 5], [1, 3, 4]]
ys=[[6, 5, 2], [6, 5, 7]]

2) Your figure

p = figure(plot_width=300, plot_height=300)

3) Make a for loop throgh the above lists and show

for (colr, leg, x, y ) in zip(colors_list, legends_list, xs, ys):
    my_plot = p.line(x, y, color= colr, legend= leg)
    
show(p)

Maintainer Note: PR #8218 which will be merged for Bokeh 1.0, allows legends to be created directly for multi line and patches, without any looping or using separate line calls.


multi_line is intended for conceptually single things, that happen to have multiple sub-components. Think of the state of Texas, it is one logical thing, but it has several distinct (and disjoint) polygons. You might use Patches to draw all the polys for "Texas" but you'd only want one legend overall. Legends label logical things. If you want to label several lines as logically distinct things, you will have to draw them all separately with p.line(..., legend_label="...")

Tags:

Bokeh