\

動的グラフの作成

PythonのMatplotlibライブラリを使用して動的なグラフを作成する方法を紹介します。この記事は、PythonとMatplotlibの基本的な知識があることを前提としています。

基本的なグラフの作成

まずは、基本的なグラフを作成してみましょう。以下のコードは、sinとcos関数のグラフを描画します。

import matplotlib.pyplot as plt
import numpy as np

# データ生成
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# プロット領域(Figure, Axes)の初期化
plt.figure(figsize=(12, 8))
fig1=plt.subplot(131)
fig2=plt.subplot(132)
fig3=plt.subplot(133)

# 棒グラフの作成
fig1.bar([1,2,3],[3,4,5])
fig1.set_xlabel("x")
fig1.set_ylabel("y")

fig2.barh([0.5,1.5,2.5],[0.5,1,2])
fig2.set_xlabel("xbar")
fig2.set_ylabel("ybar")
fig2.set_xlim(0,3)
fig2.set_ylim(0,3)

fig3.scatter(y1, y2)
plt.xlabel("sin(x)")
plt.ylabel("cos(x)")
plt.xlim(-1.2,1.2)
plt.ylim(-1.5,1.5)

plt.show()

動的なグラフの作成

次に、動的なグラフを作成してみましょう。以下のコードは、sinとcos関数のグラフを動的に描画します。

import matplotlib.pyplot as plt
import numpy as np

# プロット領域(Figure, Axes)の初期化
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(224)
ax1.axis([-1.2, 1.2, -1.2, 1.2])

# 棒グラフの作成
s = 1
while True:
    fig.delaxes(ax2)
    fig.delaxes(ax3)

    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(224)
    ax2.axis([-2.2, 2.2, -2.2, 2.2])
    ax3.axis([-1.2, 1.2, -1.2, 1.2])

    y1 = np.sin(s/10)*np.exp(-s/1000)
    y2 = np.cos(s/10)*np.exp(-s/1000)
    y3 = np.sin(s/10)
    y4 = np.cos(s/10)

    ax1.scatter(y1, y2)
    ax2.scatter(y1+y4, y2+y3)
    ax3.scatter(y4, y3)

    plt.pause(0.001)
    s += 1

このコードを実行すると、sinとcos関数のグラフが動的に描画されます。plt.pause(0.001)の部分で描画速度を調整できます。

以上がPythonとMatplotlibを用いた動的グラフの作成方法です。この知識を活用して、さまざまなデータビジュアライゼーションを試してみてください。.

投稿者 admin

コメントを残す

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