将自定义图例添加到散景栏

Add custom legend to bokeh Bar

我有 pandas 个系列:

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

我想在 Bokeh 中绘制条形图:p = Bar(etypes)。然而,对于图例,我只得到 etypes 索引号,我试图用这本字典对其进行解密:

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

通过将其传递给标签参数:p = Bar(etypes, label=legend),但它不起作用。也传递 list(legend.values()) 不起作用。

关于如何在散景条形图的 pandas 系列上添加自定义图例有什么想法吗?

*Bokeh 项目维护者的注意事项: 此答案指的是已过时且已弃用的 API。有关使用现代且完全支持的 Bokeh APIs 创建条形图的信息,请参阅其他回复。


将系列转换为 DataFrame,将图例添加为新列,然后在标签的引号中引用该列名称。例如,如果您调用 DataFrame 'etypes'、数据列 'values' 和图例列 'legend':

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

如果您绝对必须使用系列,可以将系列传递到数据对象中,然后将其传递到 bokeh。例如:

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

bokeh.charts API(包括 Bar)已于 2017 年弃用并从 Bokeh 中删除。它不受维护和支持,此时不应出于任何原因使用。使用您的数据的带有图例的条形图可以使用得到良好支持的 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)

有关 bokeh.plotting 中对条形图和分类图的大幅改进支持的详细信息,请参阅详尽的用户指南部分 Handling Categorical Data