はじめに
matplotlibのimshowで表示した2つの画像上に共通する十字カーソルを表示する方法について説明する。
コード

解説
モジュールのインポートなど
%matplotlibでjupyter lab, notebook内ではなく、別ウインドウでQt5Aggのbackendにより表示する。
バージョン
class DoubleCursorの作成
コンストラクタ
self.lx = ax.axhline(color=’g’)で水平な線を表示し、self.ly = ax.axvline(color=’g’)で垂直な線を表示させる。ax2についても同様に処理する。
ax, ax2をそれぞれself.ax, self.ax2とする。
mouse_moveの設定
if not event.inaxes: returnでax内にカーソルがない場合はなにもしないようにする。
event.xdata, event.ydataでカーソルの現在位置をそれぞれx,yとして取得する。
self.lx.set_ydata(y)で水平線のデータをyの値でセットし、self.ly.set_xdata(x)で垂直線のデータをxの値でセットする。ax2の水平線と垂直線も同様に処理する。
self.ax.set_titleでx,yの値をタイトルに表示し、self.ax.figure.canvas.draw()で図を更新する。
図の表示
fig.canvas.mpl_connectで(‘motion_notify_event’)を実行し、d_cursorのmouse_move内のコードをカーソルを動かすたびに実行させる。

参考
Cursor Demo — Matplotlib 3.1.3 documentation

[matplotlib] 72. マウスカーソルのxの位置に最も近いデータに十字カーソルを合わせる(motion_notify_event)
matplotlibのmotion_notify_eventを使って、マウスカーソルのxの位置に最も近いデータに十字カーソルを合わせる方法について説明する。
コメント