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

未设置y_range.start时Bokeh hover对值0失效的问题求助

Bokeh Hover Tool Not Showing Value 0 When y_range.start Isn't Set or Is Negative

这不是你的操作失误,而是Bokeh的默认交互检测逻辑导致的!具体原因是:Bokeh的hover工具默认会忽略高度为0或者完全处于y轴可视范围外的图形元素——当你没手动设置y_range.start时,Bokeh会自动计算y轴范围,此时0值刚好处于可视范围的边界临界点,被判定为"不可交互元素";而当你把y_range.start设为负数时,0对应的条形虽然在可视范围内,但它的高度仍然是0,还是会被hover工具的默认逻辑跳过。

两种解决办法

根据你的需求场景,可以选择以下任意一种方案:

  1. 强制锁定y轴起始值为0
    这是你已经发现的有效方案,明确设置p.y_range.start = 0后,0值的条形会被纳入可视范围的正常区域,hover工具就能正确识别并显示数值了。只需在你的代码里添加这一行即可。

  2. 自定义HoverTool的交互策略(适配负y轴场景)
    如果你确实需要y轴包含负数范围,可以通过修改HoverTool的point_policy参数,强制让hover工具跟随鼠标位置显示对应数据,不管元素高度是否为0。修改后的代码示例如下:

    from bokeh.io import show, output_file
    from bokeh.models import ColumnDataSource, HoverTool
    from bokeh.palettes import Spectral6
    from bokeh.plotting import figure
    from bokeh.transform import factor_cmap
    
    output_file("colormapped_bars.html")
    
    fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
    counts = [5, 3, 0, 2, 5, 6]
    data = {'fruits' : fruits, 'counts' : counts}
    
    source = ColumnDataSource(data=dict(fruits=fruits, counts=counts))
    
    # 自定义HoverTool,设置point_policy为follow_mouse
    hover = HoverTool(tooltips="Count: @counts", point_policy="follow_mouse")
    p = figure(x_range=fruits, plot_height=250, toolbar_location=None, title="Fruit Counts", tools=[hover])
    p.vbar(x='fruits', top='counts', width=0.9, source=source, legend="fruits", line_color='white', fill_color=factor_cmap('fruits', palette=Spectral6, factors=fruits))
    p.xgrid.grid_line_color = None
    # 测试负y轴范围
    p.y_range.start = -5
    
    show(p)
    

    运行这段代码后,即使y轴起始值是-5,鼠标悬停在Nectarines上时也能正常显示计数'0'。

内容的提问来源于stack exchange,提问作者Yogendra Vara Prasad Mummaneni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:33:02