\

Pythonのmatplotlibライブラリを使って、複数のグラフを一括で作成する方法を紹介します。この方法は、特に大量のデータを視覚化する際に非常に便利です。

まず、必要なライブラリをインポートします。

import numpy as np
import matplotlib.pyplot as plt
import math

次に、グラフ用のデータを作成します。ここでは、numpylinspace関数を使って、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文を使うことで、複数のグラフを一括で作成することが可能です。これは、大量のデータを一度に視覚化する際に非常に便利な方法です。.

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です