Matplotlibの図のタイトル#
※記事内に商品プロモーションを含むことがあります。
公開日
この記事では、Matplotlibのグラフタイトルの設定方法を説明します。 Matplotlibのグラフでは、1つのFigureの内部に、1つ以上のサブプロットを表示できます。 このFigureとサブプロットのそれぞれにタイトルを表示できます。
Figureにタイトルを設定する場合、Figure.suptitle()
メソッドを使用します。
一方、サブプロットにタイトルを設定する場合、Axes.set_title()
メソッドを使用します。
以下に例を示します。
import matplotlib.pyplot as plt
x = [5, 1, 4, 3]
fig, ax = plt.subplots()
ax.plot(x)
fig.suptitle("Figure title")
ax.set_title("Subplot title")
plt.show()

複数のサブプロットにタイトルを設定する例を以下に示します。
fig, ax = plt.subplots(nrows=2, ncols=2)
for i in range(2):
for j in range(2):
ax[i,j].plot(x)
ax[i,j].set_title(f"Subplot title {i}, {j}")
fig.suptitle("Figure title")
fig.tight_layout()
plt.show()

Figureのタイトル#
Figureにタイトルを設定するFigure.suptitle()
メソッドの主なオプションを以下に示します。
x
(float): タイトルのx座標(デフォルト値:0.5)y
(float): タイトルのy座標(デフォルト値:0.98)horizontalalignment
,ha
(str): タイトルのx方向の位置(center
(デフォルト),left
,right
)verticalalignment
,va
(str): タイトルのy方向の位置(top
(デフォルト),center
,bottom
,baseline
)fontsize
,size
(float/str): フォントサイズ。数値またはxx-small
,x-small
,small
,smaller
,medium
,large
(デフォルト),x-large
,xx-large
fontweight
,weight
(float/str): フォントの太さ。数値(0-1000)またはultralight
,light
,normal
(デフォルト),regular
,book
,medium
,roman
,semibold
,demibold
,demi
,bold
,heavy
,extra bold
,black
タイトルを左寄せの太字にした例を以下に示します。
fig, ax = plt.subplots()
ax.plot(x)
fig.suptitle("Figure title", horizontalalignment="left", x=0.2, weight="bold")
ax.set_title("Subplot title")
plt.show()

Figureのタイトルをグラフの下側に表示するには、y
オプションを用います。
fig, ax = plt.subplots()
ax.plot(x)
fig.suptitle("Figure title", y=0)
ax.set_title("Subplot title")
plt.show()

サブプロットのタイトル#
サブプロットにタイトルを設定するAxes.set_title()
メソッドの主なオプションを以下に示します。
fontdict
(dict): タイトルの設定。辞書のキーは以下の通り。fontsize
,size
(float/str): フォントサイズ。数値またはxx-small
,x-small
,small
,smaller
,medium
,large
(デフォルト),x-large
,xx-large
fontweight
,weight
(float/str): フォントの太さ。数値(0-1000)またはultralight
,light
,normal
(デフォルト),regular
,book
,medium
,roman
,semibold
,demibold
,demi
,bold
,heavy
,extra bold
,black
color
(str): 文字の色horizontalalignment
,ha
(str): タイトルのx方向の位置(center
(デフォルト),left
,right
)verticalalignment
,va
(str): タイトルのy方向の位置(top
(デフォルト),center
,bottom
,baseline
)
loc
(str): 文字のx方向の位置(center
(デフォルト),left
,right
)y
(float): タイトルのy座標(1
がトップ。デフォルト値:None
)pad
(float):Axes
上部からのオフセット(デフォルト値:6.0
)
タイトルを左寄せの太字にした例を以下に示します。
fig, ax = plt.subplots()
ax.plot(x)
fig.suptitle("Figure title")
ax.set_title("Subplot title", fontdict={"weight": "bold"}, loc="left")
plt.show()

サブプロットのタイトルをグラフの下側に表示するには、y
オプションを用います。
fig, ax = plt.subplots()
ax.plot(x)
fig.suptitle("Figure title")
ax.set_title("Subplot title", y=-0.2)
plt.show()
