JavaScriptを有効にしてください

Matplotlibでグラフの軸の目盛りを整数にする

 ·   1 min read

はじめに

Matplotlibでグラフの軸の目盛りを整数にするには、MaxNLocatorクラスを使用します。

検証環境は以下の通りです。

ソフトウェア バージョン
Python 3.9.7
matplotlib 3.4.3

軸の目盛りを整数にする

軸の目盛りを整数にするには、set_major_locatorメソッドにMaxNLocator(integer=True)を渡します。x軸を整数にする例を以下に示します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

x = [0,1,3]
y = [0,5,2]

fig, ax = plt.subplots()
ax.plot(x, y)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.show()

実行結果

x軸を整数にしたグラフ

なお、ax.xaxis.set_major_locator(MaxNLocator(integer=True))を削除すると、以下のようにx軸は小数になります。

x軸が小数のグラフ

y軸の目盛りを整数にする場合は以下のようにします。

1
ax.yaxis.set_major_locator(MaxNLocator(integer=True))

もしくは、以下のようにget_xaxis(), get_yaxis()メソッドを使っても同じ結果になります。

1
2
ax.get_xaxis().set_major_locator(MaxNLocator(integer=True))
ax.get_yaxis().set_major_locator(MaxNLocator(integer=True))

参考リンク

シェアする

Helve
WRITTEN BY
Helve
関西在住、電機メーカ勤務のエンジニア。X(旧Twitter)で新着記事を配信中です

サイト内検索