Search code examples
pythonpandasbokeh

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?


Solution

  • *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')