fontsize=Xか{“fontsize”:X}か?
前回から、matplotlibでフォントサイズを指定するのは「fontsize=X」か「{“fontsize”:X}」か、色々なコマンドに対して試しています。

今回は軸名を表示するxlabel、ylabel、set_xlabel、set_ylabelに対して試してみましょう。
まずは基本となるプログラムから。
xlabel、ylabelは普通のグラフで用いるコマンドなので、こちらのグラフで試してみましょう。
from matplotlib import pyplot as plt
y_value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 1028]
x_value = range(1, len(y_value)+1)
plt.plot(x_value, y_value)
plt.xlabel("xlabel")
plt.ylabel("ylabel")
plt.show()
実行結果

しかしset_xlabel、set_ylabelはこのグラフでは使えません。
from matplotlib import pyplot as plt
y_value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 1028]
x_value = range(1, len(y_value)+1)
plt.plot(x_value, y_value)
plt.set_xlabel("xlabel")
plt.set_ylabel("ylabel")
plt.show()
実行結果
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-8c6e65fe932f> in <module>
6 plt.plot(x_value, y_value)
7
----> 8 plt.set_xlabel("xlabel")
9 plt.set_ylabel("ylabel")
10
AttributeError: module 'matplotlib.pyplot' has no attribute 'set_xlabel'
set_xlabel、set_ylabelはsubplotsで複数のグラフを表示したときに使用したので、今回はこんな感じのプログラムを準備してみました。
from matplotlib import pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
y2 = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
fig = plt.figure()
axes= fig.subplots(2)
axes[0].plot(x, y1)
axes[1].plot(x, y2)
axes[1].set_xlabel("xlabel")
axes[0].set_ylabel("ylabel")
plt.show()
実行結果

それでは試していきましょう。
xlabel、ylabelのフォントサイズ
今回はxlabel、ylabelとフォントサイズを指定するものが二つあるので、「fontsize=X」と「{“fontsize”:X}」の両方を一度に試してみます。
from matplotlib import pyplot as plt
y_value = [1, 2, 4, 8, 16, 32, 64, 128, 256, 1028]
x_value = range(1, len(y_value)+1)
plt.plot(x_value, y_value)
plt.xlabel("xlabel", {"fontsize":20})
plt.ylabel("ylabel", fontsize=20)
plt.show()
実行結果

X軸名、Y軸名ともに大きくなりました。
ということはxlabel、ylabelに対しては「fontsize=X」でも「{“fontsize”:X}」でもどちらでもよいということになります。
set_xlabel、set_ylabelのフォントサイズ
set_xlabel、set_ylabelも「fontsize=X」と「{“fontsize”:X}」の両方を一度に試してみます。
from matplotlib import pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
y2 = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
fig = plt.figure()
axes= fig.subplots(2)
axes[0].plot(x, y1)
axes[1].plot(x, y2)
axes[1].set_xlabel("xlabel", {"fontsize":20})
axes[0].set_ylabel("ylabel", fontsize=20)
plt.show()
実行結果

こちらも両方ともフォントサイズが変わり、どちらでも良いことが分かりました。
まとめ
今回はxlabel、ylabel、set_xlabel、set_ylabelに対して、フォントサイズの指定方法を「fontsize=X」と「{“fontsize”:X}」を試してみました。
結論としてはどちらでもよいというちょっと面白くない結果になってしまいました。
ということでここまでの結果を表にまとめるとこんな感じ。
fontsize=X | {“fontsize”:X} | |
title | ○ | ○ |
suptitle | ○ | × |
xlabel ylabel | ○ | ○ |
set_xlabel set_ylabel | ○ | ○ |
今のところは「fontsize=X」が一歩リードと言ったところでしょうか。
次回は凡例を表示するlegend、軸の数値のフォントを変えるtick_paramsを試してみましょう。

ということで今回はこんな感じで。
コメント