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

user187205 picture user187205 · Jul 15, 2015 · Viewed 12.1k times · Source

I'm trying to add legend to a figure, which contains two lines created by multi_line method. Example:

p = figure(plot_width=300, plot_height=300)
p.multi_line(xs=[[4, 2, 5], [1, 3, 4]], ys=[[6, 5, 2], [6, 5, 7]], color=['blue','yellow'], legend="first")

In this case the legend is only for the first line. When the legend is defined as a list there is an error:

p.multi_line(xs=[[4, 2, 5], [1, 3, 4]], ys=[[6, 5, 2], [6, 5, 7]], color=['blue','yellow'], legend=["first","second"])

Is it possible to add legend to many lines?

Answer

Leo picture Leo · Apr 26, 2016

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)