Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom legend to bokeh Bar

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?

like image 474
vedar Avatar asked Oct 21 '25 08:10

vedar


2 Answers

*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')
like image 162
Grr Avatar answered Oct 23 '25 23:10

Grr


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)

enter image description here

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

like image 27
bigreddot Avatar answered Oct 23 '25 23:10

bigreddot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!