0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

グリッド線と軸の範囲を設定しよう〜初心者向けMatplotlib講座 #7〜

0
Posted at

前回は複数のグラフを1つのAxesに表示する方法を学びました。今回はグリッド線の表示と軸の範囲を設定して、グラフをさらに読みやすくしていきましょう。

前回の記事はこちら(リンク)

目次

  1. 出発点:前回の完成形
  2. グリッド線を表示する
  3. 軸の範囲を設定する
  4. 完成形:全部まとめて書く

出発点:前回の完成形

前回の完成形コードを出発点にします。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

ax.plot(x, y1, color="blue", label="sin(x)")
ax.plot(x, y2, color="red",  label="cos(x)")

ax.set_title("sin(x) and cos(x)")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()

グリッド線を表示する

グリッド線を表示するにはax.grid()を使います。

ax.grid(True)

Trueを渡すと表示、Falseを渡すと非表示になります。

グリッド線のスタイルを変える

グリッド線も前回学んだ線と同様に、色やスタイルを変えることができます。

ax.grid(True, color="gray", linestyle="--", linewidth=0.5)

薄めのグリッド線にしておくと、データの線が見やすくなります。linewidth0.5など小さめの値がおすすめです。

軸の範囲を設定する

デフォルトではMatplotlibがデータに合わせて自動で軸の範囲を決めてくれます。しかし「x軸を0〜5の範囲だけ表示したい」など、範囲を自分で指定したい場面もあります。

x軸の範囲はax.set_xlim()、y軸の範囲はax.set_ylim()で指定します。

ax.set_xlim(0, 5)    # x軸を0〜5に設定
ax.set_ylim(-1.5, 1.5)  # y軸を-1.5〜1.5に設定

引数は(最小値, 最大値)の順番です。

sinとcosの値は-1〜1の範囲に収まるので、set_ylim(-1.5, 1.5)とすると上下に少し余白ができて見やすくなります。

完成形:全部まとめて書く

import matplotlib.pyplot as plt
import numpy as np

# ① Figureを作る
fig = plt.figure()

# ② Axesを作る
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

# ③ データ作成
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# ④ Axesにプロット
ax.plot(x, y1, color="blue", label="sin(x)")
ax.plot(x, y2, color="red",  label="cos(x)")

# ⑤ 装飾
ax.set_title("sin(x) and cos(x)")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()

# ⑥ グリッド線
ax.grid(True, color="gray", linestyle="--", linewidth=0.5)

# ⑦ 軸の範囲
ax.set_xlim(0, 10)
ax.set_ylim(-1.5, 1.5)

# ⑧ 表示
plt.show()

表示結果

image.png

今回追加した内容を整理するとこうなります:

メソッド 役割
ax.grid(True) グリッド線を表示する ax.grid(True, linestyle="--")
ax.set_xlim(min, max) x軸の範囲を設定する ax.set_xlim(0, 10)
ax.set_ylim(min, max) y軸の範囲を設定する ax.set_ylim(-1.5, 1.5)

まとめ

  • グリッド線はax.grid(True)で表示できる
  • グリッド線のスタイルもcolorlinestylelinewidthで変えられる
  • 軸の範囲はax.set_xlim()ax.set_ylim()(最小値, 最大値)の順に指定する
  • 範囲を指定しない場合はMatplotlibが自動で決めてくれる

次回は複数のAxesを1つのFigureに並べる方法を見ていきます!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?