Matplotlibの軸の設定

Matplotlibの軸の設定#

公開日

このページではMatplotlibの軸の設定について解説します。

軸のラベル#

軸にラベルを表示するには、x軸ではax.set_xlabel()メソッド、y軸ではax.set_ylabele()メソッドを使用します。以下に例を示します。

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [4, 5, 6])
ax.set_xlabel("X axis")
ax.set_ylabel("Y axis")
plt.show()
../_images/79aaf35d379558ba07e7a1cbe4928ff0d4b7f647f7223a925f7121524162cf90.png

また、ax.set_xlabel(), ax.set_xlabel()メソッドの主なオプションを以下に示します。

オプション

説明

labelpad

float

ラベルと軸の距離(デフォルト:4)

loc

str

ラベルの位置。'center'(デフォルト)、'left', 'right'から選択

color

str

文字の色

size

float/str

文字の大きさ

fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [4, 5, 6])
ax.set_xlabel("X axis", labelpad=20, loc="left")
ax.set_ylabel("Y axis", color="red", size=15)
plt.show()
../_images/bc7a6b819e314febc1c297bb203679a99b972d7f4c605bcad9c3201bca693bc1.png

軸の範囲#

軸の範囲を指定するには、x軸ではax.set_xlim()メソッド、y軸ではax.set_ylim()メソッドを使用します。最初の引数に軸の下限値を、2番目の引数に上限値を与えます。

fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [4, 5, 6])
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
plt.show()
../_images/2eaebeb00e83a439ff1d6a502eb858943942ad0575b64694486a4af1fa15d080.png

軸の下限値か上限値の片方のみ指定したい場合、自動的に決めて欲しい側にNoneを与えます。

fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [4, 5, 6])
ax.set_xlim(None, 10)
ax.set_ylim(-10, None)
plt.show()
../_images/ad48b8d8cbe0811e8809a23ebccd355c8238f2783195481dc2153d300b6e858f.png

また、下限値を上限値より大きくした場合、軸が反転します。以下はx軸を反転させた例です。

fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [4, 5, 6])
ax.set_xlim(10, -10)
ax.set_ylim(-10, 10)
plt.show()
../_images/f5d5392ed76318ba430894f0586937e5b758f587c00b24520b41b5f642b1835b.png

複数の軸#

2つのy軸があるグラフを作成する場合、ax.twinx()メソッドを用います。反対に、2つのx軸があるグラフを作成する場合、ax.twiny()メソッドを用います。それぞれのメソッドの戻り値はAxesオブジェクトとなります。それぞれ例を以下に示します。

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 4], label="Left axis")
ax2 = ax.twinx()
ax2.scatter([1, 2, 3], [16, 14, 15], label="Right axis", c="red")
fig.legend()
plt.show()
../_images/0238585ad42a56880c1bed11f6d6ab2cb9e10dd7bd34388b7c238cacda410bf1.png
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 3, 2] , label="Lower axis")
ax2 = ax.twiny()
ax2.scatter([11, 12, 13], [3, 2, 1.5], label="Upper axis", c="red")
fig.legend()
plt.show()
../_images/76bd4f24ad1cc6d8a887e2a6471f0ebd0cb418089a835ac2d2b3962aa3803ef2.png

対数グラフ#

軸を対数にするには、x軸ではax.set_xscale()メソッド、y軸ではax.set_yscale()メソッドを使用します。これらのメソッドのオプションに"log"を指定します。以下はx軸を対数にした例です。

fig, ax = plt.subplots()
ax.scatter([1, 10, 100], [4, 5, 6])
ax.set_xscale("log")
plt.show()
../_images/a42e5c4db21480f4972bfc5cdfd42d1439d73fb45eb0b8f90ce3ebb846cbce85.png

また、baseオプションで対数の「底」を指定できます。以下は底を2とした例です。x軸は2の累乗(2^1, 2^2, 2^3, 2^4)=(2, 4, 8, 16)となっています。

fig, ax = plt.subplots()
ax.scatter([2, 4, 8, 16], [4, 5, 6, 7])
ax.set_xscale("log", base=2)
plt.show()
../_images/a3e056b2b3ac1317e49a4efb5359efce2bec065301be4d8ae02895d62151f7e5.png