Loading [MathJax]/extensions/tex2jax.js

[matplotlib] 99. supxlabel,supylabelによる共通x,yラベルの設定

matplotlib

はじめに

matplotlibのsubplotsなどで作成した複数の図の軸ラベルが同じ場合、まとめて表示した方が見やすくなる。ここでは共通のxラベル、yラベルを表示できる、supxlabel,supylabelについて説明する。

コード

import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(2, 2, figsize=(6, 6), constrained_layout=True,
sharex=True, sharey=True,dpi=150)
for nn, ax in enumerate(axs.flat):
ax.set_title(nn)
ax.imshow(np.random.rand(32,32),cmap="terrain")
fig.supxlabel('supxlabel X')
fig.supylabel('supylabel Y')
fig.suptitle('suptitle')
plt.savefig("suplabel_1.png", dpi=130)
plt.show()
view raw suplabel.py hosted with ❤ by GitHub

解説

モジュールのインポートなど

import matplotlib.pyplot as plt
import numpy as np
view raw suplabel.py hosted with ❤ by GitHub

バージョン

#version
import matplotlib
print(matplotlib.__version__)
3.4.1
print(np.__version__)
1.20.2
view raw suplabel.py hosted with ❤ by GitHub

supxlabel,supylabelを用いた図の表示

fig, axs = plt.subplots(2, 2, figsize=(6, 6), constrained_layout=True,
sharex=True, sharey=True,dpi=150)
for nn, ax in enumerate(axs.flat):
ax.set_title(nn)
ax.imshow(np.random.rand(32,32),cmap="terrain")
fig.supxlabel('supxlabel X')
fig.supylabel('supylabel Y')
fig.suptitle('suptitle')
plt.savefig("suplabel_1.png", dpi=130)
plt.show()
view raw suplabel.py hosted with ❤ by GitHub

fig.supxlabel(‘supxlabel X’)のようにすることで表示できる。なお、全体に共通するタイトルはfig.suptitle(‘suptitle’)で表示できる。

4 x 4 の図の場合

fig, axs = plt.subplots(4, 4, figsize=(6, 6), constrained_layout=True,
sharex=True, sharey=True,dpi=150)
for nn, ax in enumerate(axs.flat):
ax.set_title(nn)
ax.imshow(np.random.rand(16,16),cmap="gist_earth")
fig.supxlabel('supxlabel X')
fig.supylabel('supylabel Y')
fig.suptitle('suptitle')
plt.savefig("suplabel_2.png", dpi=130)
plt.show()
view raw suplabel.py hosted with ❤ by GitHub

3 x 3の図の場合、縦、横それぞれの真ん中の図にラベルを設定すれば良いが、4×4の図だとそうすることができないので、supxlabel, supylabelの利用は便利な方法だと思う。

コードをダウンロード(.pyファイル)

コードをダウンロード(.ipynbファイル)

参考

matplotlib.figure — Matplotlib 3.10.0 documentation
matplotlib.figure — Matplotlib 3.10.0 documentation

コメント