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

如何使用Bokeh添加第3、4、5个Y轴?

在Bokeh中实现多Y轴图表

完全可以在Bokeh中实现多Y轴(两个以上)的图表,核心是为每个额外Y轴分配独立的Range1d范围,通过y_range_name将数据系列与对应轴绑定,再用add_layout把轴添加到图表上。

以下是实现步骤和示例代码:

  • 导入依赖模块

    from bokeh.plotting import figure, show, output_notebook
    from bokeh.models import ColumnDataSource, LinearAxis, Range1d
    
  • 准备数据
    假设有三组不同量级的数据,分别对应三个Y轴:

    x = [1, 2, 3, 4, 5]
    y1 = [10, 20, 30, 40, 50]
    y2 = [1000, 2000, 3000, 4000, 5000]
    y3 = [0.1, 0.2, 0.3, 0.4, 0.5]
    
    source = ColumnDataSource(data=dict(x=x, y1=y1, y2=y2, y3=y3))
    
  • 创建主图表并配置第一个Y轴
    主图表默认的Y轴作为第一个轴,设置其标签和样式:

    p = figure(x_axis_label='X轴', y_axis_label='Y1轴', width=800, height=400)
    p.line('x', 'y1', source=source, color='blue', line_width=2)
    
  • 添加第二个Y轴
    定义新的范围,添加轴到右侧,绑定对应数据系列:

    p.extra_y_ranges['y2_range'] = Range1d(start=0, end=6000)
    p.add_layout(LinearAxis(y_range_name='y2_range', axis_label='Y2轴'), 'right')
    p.line('x', 'y2', source=source, color='red', line_width=2, y_range_name='y2_range')
    
  • 添加第三个Y轴
    重复类似步骤,通过offset参数调整轴的位置避免重叠:

    p.extra_y_ranges['y3_range'] = Range1d(start=0, end=0.6)
    p.add_layout(LinearAxis(y_range_name='y3_range', axis_label='Y3轴', offset=50), 'right')
    p.circle('x', 'y3', source=source, color='green', size=8, y_range_name='y3_range')
    
  • 显示图表

    output_notebook()  # Jupyter环境中使用,非Jupyter环境可替换为output_file
    show(p)
    

关键注意点:每个额外的Y轴必须设置唯一的y_range_name,数据系列通过该参数关联到对应轴;利用offset参数调整轴的位置可防止多个右侧轴重叠;为每个轴和对应数据系列设置相同颜色,能提升图表可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:10:33