标签未出现在 python 散景条形图中

Labels not appearing in python bokeh bar plot with groups

我想在栏上方添加带有值的标签,如下所示: 但不知道该怎么做。我的代码看起来与其他示例不同,代码可以正常工作,但可能不是正确的方法。

我的代码:

from bokeh.io import export_png
from bokeh.io import output_file, show
from bokeh.palettes import Spectral5
from bokeh.plotting import figure
from bokeh.sampledata.autompg import autompg_clean as df
from bokeh.transform import factor_cmap
from bokeh.models import ColumnDataSource, ranges, LabelSet, Label
import pandas as pd

d = {'lvl': ["lvl1", "lvl2", "lvl2", "lvl3"],
   'feature': ["test1", "test2","test3","test4"],
     'count': ["5", "20","8", "90"]}
dfn = pd.DataFrame(data=d)
sourceframe = ColumnDataSource(data=dfn)

groupn = dfn.groupby(by=['lvl', 'feature'])
index_cmapn = factor_cmap('lvl_feature', palette=Spectral5, factors=sorted(dfn.lvl.unique()), end=1)


pn = figure(plot_width=800, plot_height=300, title="Count",x_range=groupn, toolbar_location=None)

labels = LabelSet(x='feature', y='count', text='count', level='glyph',x_offset=0, y_offset=5, source=sourceframe, render_mode='canvas',)


pn.vbar(x='lvl_feature', top="count_top" ,width=1, source=groupn,line_color="white", fill_color=index_cmapn, )

pn.y_range.start = 0
pn.x_range.range_padding = 0.05
pn.xgrid.grid_line_color = None
pn.xaxis.axis_label = "levels"
pn.xaxis.major_label_orientation = 1.2
pn.outline_line_color = None
pn.add_layout(labels)
export_png(pn, filename="color.png")

我认为这与我的dfn.groupby(by=['lvl', 'feature'])和(可能是错误的)sourceframe = ColumnDataSource(data=dfn)有关。

此时剧情:

您可以像这样在初始字典中添加群组名称:

d = {'lvl': ["lvl1", "lvl2", "lvl2", "lvl3"],
     'feature': ["test1", "test2","test3","test4"],
     'count': ["5", "20","8", "90"],
     'groups': [('lvl1', 'test1'), ('lvl2', 'test2'), ('lvl2', 'test3'), ('lvl3', 'test4')]}

然后使用组的 x 值调用 LabelSet。

labels = LabelSet(x='groups', y='count', text='count', level='glyph',x_offset=20, y_offset=0, source=sourceframe, render_mode='canvas',)

这样标签就出现了。请注意,我对偏移量进行了一些调整以检查是否是问题所在,您可以手动修复它。