Matplotlibによるグラフ作成 第1回
PythonのMatplotlibを使用した基本的なグラフ作成方法を紹介する
今回は、plt記法(pyplot記法) と ax記法(オブジェクト指向記法) を紹介する
Matplotlibでのグラフ作成には、2つの手法がある
下記のQiita記事に詳しく書いてあります
早く知っておきたかったmatplotlibの基礎知識、あるいは見た目の調整が捗るArtistの話 - Qiita
今回は、両方の方法でグラフを作成していきます
今回の例だと、どちらも同じグラフが作成できますが、
個人的には、細部にもこだわりたいので ax記法 を使っています
plt記法
plt記法では、pltを主に使用して、グラフを描いていきます
使用者は、対象のオブジェクトを意識せずにグラフを描くことができる一方で、
細かいグラフの設定は難しくなる
import matplotlib.pyplot as plt import numpy as np def f(t): return np.exp(-t) * np.cos(2 * np.pi * t) t1 = np.arange(0, 5, 0.1) t2 = np.arange(0, 5, 0.02) plt.figure(figsize=(6, 5)) plt.subplot(2, 1, 1) plt.plot(t1, f(t1), 'bo') plt.grid() plt.subplot(2, 1, 2) plt.plot(t2, np.cos(2 * np.pi * t2), 'r--') plt.ylim(-1.5, 2) plt.grid() plt.tight_layout()
ax記法
import matplotlib.pyplot as plt import numpy as np def f(t): return np.exp(-t) * np.cos(2 * np.pi * t) t1 = np.arange(0, 5, 0.1) t2 = np.arange(0, 5, 0.02) fig = plt.figure(figsize=(6, 5)) ax1 = fig.add_subplot(2, 1, 1) ax1.plot(t1, f(t1), 'bo') ax1.grid() ax2 = fig.add_subplot(2, 1, 2) ax2.plot(t2, np.cos(2 * np.pi * t2), 'r--') ax2.set_ylim(-1.5, 2) ax2.grid() fig.tight_layout()