はじめに
matplotlibのsubplotsなどで作成した複数の図の軸ラベルが同じ場合、まとめて表示した方が見やすくなる。ここでは共通のxラベル、yラベルを表示できる、supxlabel,supylabelについて説明する。
コード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()

解説
モジュールのインポートなど
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt
import numpy as np
バージョン
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#version
import matplotlib
print(matplotlib.__version__)
3.4.1
print(np.__version__)
1.20.2
supxlabel,supylabelを用いた図の表示
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()
fig.supxlabel(‘supxlabel X’)のようにすることで表示できる。なお、全体に共通するタイトルはfig.suptitle(‘suptitle’)で表示できる。
4 x 4 の図の場合
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()
3 x 3の図の場合、縦、横それぞれの真ん中の図にラベルを設定すれば良いが、4×4の図だとそうすることができないので、supxlabel, supylabelの利用は便利な方法だと思う。

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