Pythonのmatplotlib
ライブラリを使って、for文を用いて複数のグラフを一括で作成する方法について説明します。
まず、以下のように適当なサンプルデータを作成します。
import numpy as np
import matplotlib.pyplot as plt
import math
# グラフ用のデータ作成
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)
次に、作成したデータを一つのリストに格納します。
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文を使って一括でグラフを作成します。
# 整列させるグラフの数を指定(縦、横)
grf_row = 2
grf_col = 4
# グラフ作成
fig = plt.figure(figsize=(grf_col * 4, grf_row * 4))
ax_list = []
for j in range(grf_row):
for i in range(grf_col):
if (j * grf_col + i) < len(y_list):
ax_list.append(fig.add_subplot(grf_row, grf_col, j * grf_col + i + 1))
ax_list[j * grf_col + i].plot(x, y_list[j * grf_col + i], color='blue', label=label_list[j * grf_col + i])
ax_list[j * grf_col + i].set_xlabel('X', fontsize=14)
ax_list[j * grf_col + i].set_ylabel('Y', fontsize=14)
ax_list[j * grf_col + i].legend(loc='upper right', fontsize=14)
ax_list[j * grf_col + i].set_title(label_list[j * grf_col + i], fontsize=14)
ax_list[j * grf_col + i].set_xlim(0, 360)
ax_list[j * grf_col + i].set_ylim(-5, 5)
# グラフ間の間隔指定
plt.subplots_adjust(wspace=0.4, hspace=0.6)
plt.show()
以上がPythonでfor文を使って複数のグラフを一括で作成する方法です。この方法を使えば、大量のデータを効率よく可視化することができます。.