首页 > 解决方案 > 在 Python 中使用 Bokeh hovertool 工具提示函数可视化数据时出错

问题描述

这里的第 1 篇文章是 python 的新手,所以请放轻松!

我已经使用散景库在 python 中绘制了我的可视化。我使用了 hovertool 功能,但是当我将鼠标悬停在它上面时似乎无法显示任何数据。不知道我哪里出错了。欢迎任何支持。

散景库

from bokeh.plotting import figure, show

from bokeh.io import output_file

from bokeh.models import ColumnDataSource, NumeralTickFormatter

from bokeh.models import HoverTool

output_notebook()

将数据存储在 ColumnDataSource 中

df = ColumnDataSource(contents)

指定可用的选择工具

select_tools = ['box_select', 'lasso_select', 'poly_select', 'tap', 'reset']

创建图

fig = figure(plot_height=400,
         plot_width=600,
         x_axis_label=' Store Average Age of Respondent',
         y_axis_label=' Store NPS Percentage Score %',
         title='MNWIOM Average Customer Age Vs. NPS Percentage Score by Store',
         toolbar_location='below',
         tools=select_tools)

添加代表每个商店的正方形

fig.square(x='Average Age of Respondent',
       y='NPS Percentage Score',
       source=df,
       color='royalblue',
       selection_color='deepskyblue',
       nonselection_color='lightgray',
        nonselection_alpha=0.3)

格式化工具提示

tooltips = [('Store','@Store Name'),
        ('Average Customer Age', '@Average Age of Respondent'),
        ('NPS Score %', '@NPS Percentage Score'),]

配置要在悬停时使用的渲染器

hover_glyph = fig.circle(x='Average Age of Respondent', y='NPS Percentage Score', source=df,
                     size=15, alpha=0,
                     hover_fill_color='black', hover_alpha=0.5)

将 HoverTool 添加到图中

fig.add_tools(HoverTool(tooltips=tooltips, renderers=[hover_glyph]))

可视化

show(fig)

标签: pythonbokeh

解决方案


如果您的字段名称包含空格,则必须在工具提示定义中使用大括号 {}。从 hovertool 文档(链接):

tooltips=[
    ( 'date',   '@date{%F}'            ),
    ( 'close',  '$@{adj close}{%0.2f}' ), # use @{ } for field names with spaces
    ( 'volume', '@volume{0.00 a}'      ),
]

推荐阅读