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

如何在Bokeh>=2.4版本中为绘图图例添加Span条目?

解决Bokeh 2.4+中为Span添加图例条目的问题

在Bokeh 2.4及以上版本中,旧的无数据line glyph方法已失效,你可以通过LegendItem直接关联Span对象来实现需求,无需额外创建多余的图形元素,也不用在轴更新时重新计算位置。

实现步骤

  1. 创建目标Span对象并添加到绘图中
  2. 用LegendItem绑定Span的视觉样式或直接关联Span渲染器
  3. 将图例添加到绘图布局

代码示例

from bokeh.models import Span, Legend, LegendItem
from bokeh.plotting import figure, show

# 创建基础绘图
p = figure(x_range=(0, 10), y_range=(0, 10))
p.circle([1,2,3,4,5], [2,4,6,8,10], color='blue')

# 创建需要添加图例的Span
ref_span = Span(
    location=5,
    dimension='width',
    line_color='red',
    line_width=2,
    line_dash='dashed'
)
p.add_layout(ref_span)

# 创建关联Span的图例条目
legend_item = LegendItem(
    label="参考基准线",
    renderers=[ref_span]  # 直接绑定Span,自动继承其样式
)

# 添加图例到绘图
p.add_layout(Legend(items=[legend_item]), 'right')

show(p)

注意事项

  • 如果部分版本中renderers参数对Span不生效,可以手动指定glyph参数匹配Span样式:
    from bokeh.models import Line
    legend_item = LegendItem(
        label="参考基准线",
        glyph=Line(line_color='red', line_width=2, line_dash='dashed')
    )
    
  • 这种方式不会在绘图区域生成额外线条,完全适配轴切换和缩放操作,也无需维护Span与line的位置同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:43:16