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

浪子不回头ぞ 提交于 2019-12-17 19:37:09

问题


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?


回答1:


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="...")




回答2:


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)



回答3:


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)


来源:https://stackoverflow.com/questions/31419388/bokeh-how-to-add-legend-to-figure-created-by-multi-line-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!