Pythonの描画ライブラリである matplotlib
を用いて、複数のグラフを並べて表示する方法について紹介します。
複数のグラフを並べて表示する方法
まずは、 matplotlib
で複数のグラフを並べて表示する基本的な方法について紹介します。グラフを表示する領域を fig
オブジェクトとして作成し、複数のグラフそれぞれの領域を subplot
として指定することで、複数のグラフを並べて表示することができます。
以下に、2つのグラフを上下に並べて表示するサンプルコードを示します。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
c1, c2 = 'blue', 'green'
l1, l2 = 'sin', 'cos'
xl1, xl2 = 'x', 'x'
yl1, yl2 = 'sin', 'cos'
# グラフを表示する領域を,figオブジェクトとして作成。
fig = plt.figure(figsize = (10,6), facecolor='lightblue')
# グラフを描画するsubplot領域を作成。
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)
# 各subplot領域にデータを渡す
ax1.plot(x, y1, color=c1, label=l1)
ax2.plot(x, y2, color=c2, label=l2)
# 各subplotにxラベルを追加
ax1.set_xlabel(xl1)
ax2.set_xlabel(xl2)
# 各subplotにyラベルを追加
ax1.set_ylabel(yl1)
ax2.set_ylabel(yl2)
# 凡例表示
ax1.legend(loc = 'upper right')
ax2.legend(loc = 'upper right')
plt.show()
このコードを実行すると、sin関数とcos関数のグラフが上下に並べて表示されます。
2つ以上のグラフを並べて表示する方法
前述の方法を拡張するだけで、2×2などでグラフを並べることも簡単に実現できます。以下に、2×2で4つのグラフを並べて表示するサンプルコードを示します。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = -np.sin(x)
y4 = np.sin(x)**2
c1,c2,c3,c4 = 'blue', 'green', 'red', 'black'
l1,l2,l3,l4 = 'sin', 'cos', '-sin', 'sin**2'
xl1, xl2, xl3, xl4 = 'x', 'x', 'x', 'x'
yl1, yl2, yl3, yl4 = 'sin', 'cos', '-sin', 'sin**2'
# グラフを表示する領域を,figオブジェクトとして作成.
fig = plt.figure(figsize = (10,6), facecolor='lightblue')
# グラフを描画するsubplot領域を作成。
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)
# 各subplot領域にデータを渡す
ax1.plot(x, y1, color=c1, label=l1)
ax2.plot(x, y2, color=c2, label=l2)
ax3.plot(x, y3, color=c3, label=l3)
ax4.plot(x, y4, color=c4, label=l4)
# 各subplotにxラベルを追加
ax1.set_xlabel(xl1)
ax2.set_xlabel(xl2)
ax3.set_xlabel(xl3)
ax4.set_xlabel(xl4)
# 各subplotにyラベルを追加
ax1.set_ylabel(yl1)
ax2.set_ylabel(yl2)
ax3.set_ylabel(yl3)
ax4.set_ylabel(yl4)
# 凡例表示
ax1.legend(loc = 'upper right')
ax2.legend(loc = 'upper right')
ax3.legend(loc = 'upper right')
ax4.legend(loc = 'upper right')
plt.show()
このコードを実行すると、sin関数、cos関数、-sin関数、sin^2関数のグラフが2×2で並べて表示されます。
以上がPythonの matplotlib
ライブラリを用いて複数のグラフを並べて表示する方法です。この方法を用いることで、複数のデータを一度に視覚的に比較することが可能となります。.