我有一个数据框
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, getting COuntry of type str
.
如何解决这个问题?
最佳答案
Label
在位置 x
和 y
处生成单个标签。在您的示例中,您尝试使用 DataFrame 中的数据作为坐标来添加多个标签。这就是为什么您收到错误消息 x
和 y
需要是映射到图形 x_range 和 y_range 的真实坐标值。您应该考虑使用 LabelSet
( link ),它可以将 Bokeh ColumnDataSource
作为参数并构建多个标签。
不幸的是,您还使用了 Bokeh 条形图,它是创建分类 y_range 的高级图表。 Bokeh 目前无法在分类 y_range 上添加标签。您可以通过创建较低级别 vbar 来规避此问题。使用占位符 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)
关于python - 如何向 Bokeh 条形图添加标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45168713/