不出现在python bokeh条形图中的标签与组一起打印

不出现在python bokeh条形图中的标签与组一起打印,python,bokeh,Python,Bokeh,我想像下面这样添加带有条形图上方值的标签:但我不知道怎么做。我的代码看起来与其他示例不同,代码正常工作,但可能不是正确的方式 我的代码: 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 au

我想像下面这样添加带有条形图上方值的标签:但我不知道怎么做。我的代码看起来与其他示例不同,代码正常工作,但可能不是正确的方式

我的代码:

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有关。groupbyby=['lvl','feature']和可能错误的sourceframe=ColumnDataSourcedata=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',)
这样标签就会出现。请注意,我对偏移量进行了一些调整,以检查这是否是问题所在,您可以手动修复它


您的代码与链接的示例有何不同?您有一个数据源,您可以调用vbar—这就是您所需要的。只需使用正确的值创建标签集并将其添加到绘图中,因为我不使用ColumnDataSource创建绘图。但这是标签所需要的。我现在创建了一个标签集,但是标签没有出现在绘图中。先生,你太棒了。我假设这样做是因为'lvl1','test1'与groupn=dfn匹配。groupbyby=['lvl','feature']是的,我实际上是通过groupn迭代来获得组名的。