Pythonのmatplotlib
ライブラリを使って、複数のグラフを一括で作成する方法を紹介します。この方法は、特に大量のデータを視覚化する際に非常に便利です。
まず、必要なライブラリをインポートします。
import numpy as np
import matplotlib.pyplot as plt
import math
次に、グラフ用のデータを作成します。ここでは、numpy
のlinspace
関数を使って、0から360までの361個の等間隔の数値を生成し、それをx
とします。そして、y1
からy8
までの8つの異なるsin
関数を作成します。
x = np.linspace(0, 360, 361)
y1 = np.sin(2 * math.pi / 360 * x)
y2 = np.sin(2 * math.pi / 360 * x * 2)
y3 = np.sin(2 * math.pi / 360 * x * 3)
y4 = np.sin(2 * math.pi / 360 * x * 4)
y5 = 2 * np.sin(2 * math.pi / 360 * x)
y6 = 3 * np.sin(2 * math.pi / 360 * x)
y7 = 4 * np.sin(2 * math.pi / 360 * x)
y8 = 5 * np.sin(2 * math.pi / 360 * x)
これで、y1
からy8
までのデータを作成することができました。次に、これらのデータを一つのリストにまとめます。
y_list = [y1, y2, y3, y4, y5, y6, y7, y8]
さらに、各グラフのラベル名とタイトルもリストで作成しておきます。
label_list = ['y1', 'y2', 'y3', 'y4', 'y5', 'y6', 'y7', 'y8']
title_list = ['Y1', 'Y2', 'Y3', 'Y4', 'Y5', 'Y6', 'Y7', 'Y8']
これで、グラフを作成する準備が整いました。次に、for
文を使って、これらのデータを一括でグラフに描画します。
fig = plt.figure(figsize=(8, 4))
for i in range(len(y_list)):
ax = fig.add_subplot(2, 4, i + 1)
ax.plot(x, y_list[i], color='blue', label=label_list[i])
ax.set_xlabel('X', fontsize=14)
ax.set_ylabel('Y', fontsize=14)
ax.legend(loc='upper right', fontsize=14)
ax.set_title(title_list[i], fontsize=14)
ax.set_xlim(0, 360)
ax.set_ylim(-5, 5)
plt.subplots_adjust(wspace=0.4, hspace=0.6)
plt.show()
以上のコードを実行すると、8つの異なるsin
関数のグラフが一括で描画されます。
このように、Pythonのmatplotlib
ライブラリとfor
文を使うことで、複数のグラフを一括で作成することが可能です。これは、大量のデータを一度に視覚化する際に非常に便利な方法です。.