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/1de68bdb022ee5a6ad2979155bf5f2f5b65035fec2a4fd2661e92bb55266374c.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/f72e42b88d1da458e79264d24edd1be7322b6279d21091bf99dcf46df5180f4f.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/1d9772a5b62242b30538a310701fab0c45f3108b81a0d16cd896a30166e5e58a.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/1348849298c67790c9b8694890d6d6c216c466946b3ffa9a508230369211474c.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/ed0d071f5d7e59bb6b3d966bad426ee662e071f3d43a03ba234855b3e4e265ec.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/57eca714a21f60f4afa2e4d2a6752f4a232f106818e4d25b70aae6837eed65d9.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/54a0be4536154cbb93efbc5c92ace134f88e6d1286cf319f3e056ad8dee61ec4.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/0c8da6e0bc2fa7bed4af808168acc5c633f4eb4c2a2c6343e4a52750fc439f86.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/f62bedee6eca05e876958f1bcf5c46bb1ab2ded147d6b84572d50a734d429c08.png