萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Matplotlib 多子圖共享 X 軸游標:MultiCursor 實現跨軸垂直線聯動

需求場景

多子圖共享 X 軸(如時序數據不同指標)時,需滑鼠移動時在所有子圖顯示同一垂直游標線,便於對比不同時刻的數值。

核心代碼


import numpy as np
from matplotlib.widgets import MultiCursor
from pylab import figure, show, np

t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2 * np.pi * t)
s2 = np.sin(4 * np.pi * t)

fig = figure()
ax1 = fig.add_subplot(211)
ax1.plot(t, s1)
ax2 = fig.add_subplot(212, sharex=ax1)  # 關鍵:共享 X 軸
ax2.plot(t, s2)

# 建立跨軸游標
multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1)
show()

效果展示

紅色垂直線隨滑鼠水平移動,同步顯示於兩子圖對應 X 座標。

關鍵點解析

  • sharex=ax1:子圖共享 X 軸縮放/平移/範圍,確保座標對齊。
  • MultiCursor(canvas, axes_tuple, **line_props):掛載在畫布,監聽 motion_notify_event,在所有傳入 axes 繪製垂直線。
  • color='r', lw=1:線條樣式傳遞給 ax.axvline。

進階:自定義游標顯示座標文本


from matplotlib.widgets import Cursor

# 單軸游標 + 座標文本
cursor = Cursor(ax1, useblit=True, color='red', linewidth=1)

def on_move(event):
    if event.inaxes:
        x, y = event.xdata, event.ydata
        ax1.set_title(f"x={x:.2f}, y={y:.2f}")
        fig.canvas.draw_idle()

fig.canvas.mpl_connect('motion_notify_event', on_move)

總結

MultiCursor 以極簡 API 實現「多子圖共享 X 軸垂直游標聯動」,配合 sharex 確保座標對齊。適用於金融 K 線+成交量、多傳感器時序對比、頻譜+波形等經典分析場景。

copyright © 萬盛學電腦網 all rights reserved