【matplotlib】軸ラベルの位置を微調整したい【python】

グラフを書くときに、x軸ラベルの位置を微調整したくなった。

set_xlabelでx軸の設定を変更する際に、locという引数があり、left,center,rightを指定することで、大雑把には位置を調整できる。

ちなみにy軸であればset_ylabelでbottom, center, topで変更できる。

import matplotlib.pyplot as plt y = np.array([1, 2, 3, 4]) fig = plt.figure(figsize=(4, 4)) ax1 = fig.add_subplot(111) ax1.bar(y, y) ax1.set_xlabel("x-axis", loc="center") #locで位置を軸ラベルの変更できる。 plt.show()

 

 

ただ、これは三段階の調整なので微調整はできなかった。

色々と調べるとset_xlabelにはtextクラスで指定できるパラメーターを使えるらしく、x,yで位置を調整できることが分かった。(詳細は公式ドキュメント参照

ax1.set_xlabel("x-axis", x=0.9)

無事完成。

参考サイト

matplotlib.axes.Axes.set_xlabel — Matplotlib 3.3.3 documentation

matplotlib.text — Matplotlib 3.3.3 documentation