2017-07-18 96 views
1

我有一个数据帧作为如何将标签添加到散景条形图?

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

我想绘制带标签的条形图(即“编号”的值)注释在顶部为每个条,并相应地进行。

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: expected a value of type Real, got COuntry of type str

我该如何解决这个问题?

回答

0

Label在位置xy处产生单个标签。在你的例子中,你试图使用DataFrame中的数据作为坐标来添加多个标签。这就是为什么你要让你的错误信息xy需要是映射到图形的x_range和y_range的实坐标值。你应该考虑使用LabelSetlink),它可以将散景ColumnDataSource作为参数并构建多个标签。

毫无疑问,您还在使用一个散焦条形图,它是一个创建分类y_range的高级图表。目前,Bokeh不能将标签放在分类y_ranges上。您可以通过使用占位符x值创建较低级别的vbar图表,然后对其进行样式设置,使其与原始图表具有相同的外观,从而绕过此问题。它在行动中。

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)