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

如何在Bokeh双Y轴图表中单独缩放单个Y轴并固定另一个?

解决Bokeh双Y轴独立滚轮缩放问题

要实现两个Y轴独立缩放,你需要做好三个关键配置:给额外Y轴范围设置独立缩放策略、正确绑定渲染器到对应范围、调整滚轮缩放工具的作用范围。以下是具体步骤和修正后的代码:

1. 核心配置要点

  • 给额外Y轴的Range1d设置scaling_policy="independent",这是让两个Y轴缩放互不影响的关键。
  • 确保每个线条渲染器明确绑定到对应的Y轴范围(主Y轴默认,副Y轴需指定y_range_name)。
  • 调整滚轮缩放工具,使其能分别作用于不同的Y轴范围。

2. 修正后的完整代码示例

from bokeh.plotting import figure, curdoc
from bokeh.models import Range1d, LinearAxis, WheelZoomTool
from bokeh.models.sources import ColumnDataSource
import numpy as np

# 初始化数据源(模拟实时数据)
source_main = ColumnDataSource(data={'x': np.arange(10), 'y': np.random.rand(10)*50})
source_extra = ColumnDataSource(data={'x': np.arange(10), 'y': np.random.rand(10)*100})

# 创建主图表
plot1 = figure(x_axis_label='X轴', y_axis_label='主Y轴', tools="pan,box_zoom,reset,save")

# 配置额外Y轴及范围
extra_y_range = Range1d(start=0, end=100, scaling_policy="independent")
plot1.extra_y_ranges = {"extra_y": extra_y_range}
# 添加右侧副Y轴
plot1.add_layout(LinearAxis(y_range_name="extra_y", axis_label='副Y轴'), 'right')

# 创建线条并绑定对应Y轴范围
line1 = plot1.line('x', 'y', source=source_main, color='blue')  # 绑定主Y轴(默认)
line2 = plot1.line('x', 'y', source=source_extra, color='red', y_range_name="extra_y")  # 绑定副Y轴

# 绑定渲染器到对应范围
plot1.y_range.renderers = [line1]
plot1.extra_y_ranges["extra_y"].renderers = [line2]

# 替换默认滚轮缩放工具,添加分别作用于两个Y轴的工具
# 移除默认WheelZoomTool
plot1.toolbar.tools = [tool for tool in plot1.toolbar.tools if not isinstance(tool, WheelZoomTool)]
# 添加主Y轴滚轮缩放工具
wheel_zoom_main = WheelZoomTool(dimensions="width_height", y_range_name="default")
# 添加副Y轴滚轮缩放工具
wheel_zoom_extra = WheelZoomTool(dimensions="width_height", y_range_name="extra_y")
plot1.add_tools(wheel_zoom_main, wheel_zoom_extra)
# 设置默认激活主Y轴缩放工具,可通过工具栏切换
plot1.toolbar.active_scroll = wheel_zoom_main

# 实时更新数据的回调函数
def update_data():
    new_x = np.arange(10)
    new_y_main = np.random.rand(10)*50
    new_y_extra = np.random.rand(10)*100
    source_main.data = {'x': new_x, 'y': new_y_main}
    source_extra.data = {'x': new_x, 'y': new_y_extra}

# 添加周期性回调,每2秒更新一次
curdoc().add_periodic_callback(update_data, 2000)
curdoc().add_root(plot1)

3. 关键修正说明

  • 错误修正:你之前直接对plot1.extra_y_ranges.renderers赋值,但extra_y_ranges是字典类型,需通过键(如"extra_y")获取对应的Range1d对象后再设置renderers。
  • 缩放策略:设置scaling_policy="independent"后,额外Y轴的缩放将完全独立于主Y轴,不会随主Y轴变化。
  • 工具配置:替换默认滚轮工具为两个分别绑定不同Y轴的工具,确保鼠标操作时只会影响对应轴的缩放(可通过工具栏切换激活的工具)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:30:25