You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bokeh折线图HoverTool无法正常显示系列名称问题咨询

问题原因及解决方法

核心问题

  1. 数据源初始化错误:代码中先定义了source,随后又用未定义的data_dict重新赋值,导致数据源逻辑混乱。
  2. $name未正确绑定:$name获取的是折线渲染器(p.line)的name属性,而你仅设置了legend_label,未给每个折线指定name参数,因此HoverTool无法识别系列名称,显示为问号。

修正后的代码

import datetime as dt
from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource, HoverTool

# 正确定义数据字典并初始化数据源
data_dict = dict(
    x=[dt.datetime(2023, 1, 1), dt.datetime(2023, 1, 2), dt.datetime(2023, 1, 3), dt.datetime(2023, 1, 4), dt.datetime(2023, 1, 5)],
    y1=[2, 5, 8, 2, 7],
    y2=[3, 2, 1, 4, 7],
    y3=[1, 4, 5, 6, 3]
)
source = ColumnDataSource(data_dict)

tools = "pan,box_zoom,zoom_in,zoom_out,redo,undo,reset,crosshair"
p = figure(title = "Blah", 
           x_axis_label='date', 
           width=1600, 
           height=850,
           x_axis_type='datetime',
           tools=tools,
           toolbar_location='above')

# 循环创建折线时,同时设置name和legend_label
for c in data_dict.keys():
    if c != 'x':
        # 添加name参数,与列名一致
        p.line(x='x', y=c, source=source, legend_label=c, name=c)

p.legend.location = "top_left"
p.legend.click_policy = "hide"

# 修正格式器的键名,与tooltips里的$x格式对应
formatters_tooltips = {'$x': 'datetime'}

p.add_tools(HoverTool(
    tooltips=[('Date', '$x{%Y-%m-%d}'), ('Name', '$name'), ('Value', '$y')],
    formatters=formatters_tooltips,
    # 指定只对带有name属性的渲染器生效(可选优化)
    renderers=p.select(name=['y1', 'y2', 'y3'])
))

output_file("C:/some_path/some_file.html")
   
show(p)

其他可选方案

如果不想给每个渲染器设置name,也可以为每个折线单独配置HoverTool,直接指定系列名称:

# 移除全局HoverTool,改为循环中为每个折线添加单独的HoverTool
for c in data_dict.keys():
    if c != 'x':
        renderer = p.line(x='x', y=c, source=source, legend_label=c)
        hover = HoverTool(
            renderers=[renderer],
            tooltips=[('Date', '$x{%Y-%m-%d}'), ('Name', f'{c}'), ('Value', f'@{c}')],
            formatters={'$x': 'datetime'}
        )
        p.add_tools(hover)

内容的提问来源于stack exchange,提问作者mHelpMe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 23:16:00