はじめに
matplotlibでグラフ上にテキスト、矢印を表示する方法について説明する。text(), annotate()を用いる。
コード&解説
モジュールのインポート
バージョン
グラフの上にテキストを配置

テキストを配置するには、ax.text()を用いる。テキストを表示する位置は、transformで基準を定める。
transform=ax.transDataの場合、図のx軸、y軸の目盛に従ってテキストを配置する位置が決まる。
transform=fig.transFigureの場合、figオブジェクト全体の左下を(0,0)、右上を(1,1)とする相対的な位置で配置される。
transform=ax.transAxesの場合は、グラフの左下を(0,0)右上を(1,1)とする相対的な位置でテキストが配置される。
ylimで表示範囲をかえてもtransform=fig.transFigure、ax.transAxesの場合は位置が変化しない。

annotateによる注釈の表示

ax.annotate(‘maximum’, xy=(x[np.argmax(y)], np.max(y)), xytext=(3,5)…のようにすることで矢印付きのテキストを表示できる。
最初の”にテキストを入力し、次のxyに矢印の先端の座標、xytextにテキストの座標を入力する。
arrowpropsについて
arrowpropsを設定することで矢印の見た目を変えることができる。ここではその詳細を例とともに表示する。
shrink
shrinkで矢印を縮ませることができる。

headlength
headlengthで矢印の先端の長さが変化する。

headwidth
headwidthで矢印の先端の幅が変化する。

width
widthで矢印の棒の太さを変えることができる。

参考
matplotlib.pyplot.annotate — Matplotlib 3.10.0 documentation
コメント