Python 如何将标签添加到Bokeh条形图?

Python 如何将标签添加到Bokeh条形图?,python,plot,bar-chart,data-visualization,bokeh,Python,Plot,Bar Chart,Data Visualization,Bokeh,我有一个数据帧 df = pd.DataFrame(data = {'Country':'Spain','Japan','Brazil'],'Number':[10,20,30]}) 我想绘制一个条形图,在每个条形图的顶部标注标签(即“Number”的值),并据此进行操作 from bokeh.charts import Bar, output_file,output_notebook, show from bokeh.models import Label p = B

我有一个数据帧

df = pd.DataFrame(data = {'Country':'Spain','Japan','Brazil'],'Number':[10,20,30]})
我想绘制一个条形图,在每个条形图的顶部标注标签(即“Number”的值),并据此进行操作

    from bokeh.charts import Bar, output_file,output_notebook, show
    from bokeh.models import Label
    p = Bar(df,'Country', values='Number',title="Analysis", color = "navy")
    label = Label(x='Country', y='Number', text='Number', level='glyph',x_offset=5, y_offset=-5)
    p.add_annotation(label)    
    output_notebook()
    show(p)
但我得到了一个错误,即
ValueError:期望值为Real类型,而got COuntry为str类型


如何解决此问题?

Label
在位置
x
y
处生成一个标签。在您的示例中,您试图使用数据帧中的数据作为坐标添加多个标签。这就是为什么您会收到错误消息
x
y
必须是映射到地物x\u范围和y\u范围的真实坐标值。您应该考虑使用
LabelSet
(),它可以将Bokeh
ColumnDataSource
作为参数并构建多个标签

不幸的是,你也在使用博克条形图,这是一个高层次的图表,它创建了一个分类的y_范围。Bokeh目前无法在分类y_范围上添加标签。您可以通过使用占位符x值创建较低级别的图表,然后对其进行样式设置,使其与原始图表具有相同的外观,从而避免此问题。在这里,它正在发挥作用

import pandas as pd
from bokeh.plotting import output_file, show, figure
from bokeh.models import LabelSet, ColumnDataSource, FixedTicker

# arbitrary placeholders which depends on the length and number of labels
x = [1,2,3]
 # This is offset is based on the length of the string and the placeholder size
offset = -0.05 
x_label = [x + offset for x in x]

df = pd.DataFrame(data={'Country': ['Spain', 'Japan', 'Brazil'],
                        'Number': [10, 20, 30],
                        'x': x,
                        'y_label': [-1.25, -1.25, -1.25],
                        'x_label': x_label})

source = ColumnDataSource(df)

p = figure(title="Analysis", x_axis_label='Country', y_axis_label='Number')
p.vbar(x='x', width=0.5, top='Number', color="navy", source=source)
p.xaxis.ticker = FixedTicker(ticks=x)  # Create custom ticks for each country
p.xaxis.major_label_text_font_size = '0pt'  # turn off x-axis tick labels
p.xaxis.minor_tick_line_color = None  # turn off x-axis minor ticks
label = LabelSet(x='x_label', y='y_label', text='Number',
                 level='glyph', source=source)
p.add_layout(label)
show(p)