Add custom legend to bokeh Bar

送分小仙女□ 提交于 2021-02-07 19:56:35

问题


I have pandas series as:

>>> etypes
0    6271
1    6379
2     399
3     110
4    4184
5    1987

And I want to draw Bar chart in Bokeh: p = Bar(etypes). However for legend I get just etypes index number, which I tried to decrypt with this dictionary:

legend = {
    0: 'type_1',
    1: 'type_2',
    2: 'type_3',
    3: 'type_4',
    4: 'type_5',
    5: 'type_6',
}

by passing it to label argument: p = Bar(etypes, label=legend), but it didn't work. Also passing the list(legend.values()) does not work.

Any ideas how to add custom legend on pandas series in bokeh Bar chart?


回答1:


*Note from Bokeh project maintainers: This answer refers to an obsolete and deprecated API. For information about creating bar charts with modern and fully supported Bokeh APIs, see the other response.


Convert the series to a DataFrame, add the legend as a new column and then reference that column name in quotes for label. For example, if you call your DataFrame 'etypes', data column 'values', and your legend column 'legend':

p = Bar(etypes, values='values', label='legend') 

If you absolutely must use a series, you can pass the series into a data object and then pass that to bokeh. For example:

legend = ['type1', 'type2', 'type3', 'type4', 'type5', 'type6']
data = {
    'values': etypes
    'legend': legend
}
p = Bar(data, values='values', label='legend')



回答2:


The bokeh.charts API (including Bar) was deprecated and removed from Bokeh in 2017. It is unmaintained and unsupported and should not be used for any reason at this point. A bar chart with legend using your data can be accomplished using the well-supported bokeh.plotting API:

from bokeh.palettes import Spectral6
from bokeh.plotting import figure, show

types = ["type_%d" % (x+1) for x in range(6)]
values = [6271, 6379, 399, 110, 4184, 1987]

data=dict(types=types, values=values, color=Spectral6)

p = figure(x_range=types, y_range=(0, 8500), plot_height=250)
p.vbar(x='types', top='values', width=0.9, color='color', legend="types", source=data)

p.xgrid.grid_line_color = None
p.legend.orientation = "horizontal"
p.legend.location = "top_center"

show(p)

For more information on the vastly improved support for bar and categorical plots in bokeh.plotting, see the extensive user guide section Handling Categorical Data



来源:https://stackoverflow.com/questions/38731491/add-custom-legend-to-bokeh-bar

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