散布図を自動的に更新しようとしています。X 値と Y 値のソースは外部にあり、データは予測されない時間間隔 (ラウンド) で自動的にコードにプッシュされます。
プロセス全体が終了したときにのみすべてのデータをプロットできましたが、キャンバスにデータを常に追加してプロットしようとしています。
私のコードの簡略版:
import matplotlib.pyplot as plt
def read_data():
#This function gets the values of xAxis and yAxis
xAxis = [some values] #these valuers change in each run
yAxis = [other values] #these valuers change in each run
plt.scatter(xAxis,yAxis, label = 'myPlot', color = 'k', s=50)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
ベストアンサー1
matplotlib プロットをアニメーション化する方法がいくつかあります。以下では、散布図を使用した 2 つの簡単な例を見てみましょう。
(a) 対話モードを使用するplt.ion()
アニメーションを実行するには、イベント ループが必要です。イベント ループを取得する方法の 1 つは、plt.ion()
("interactive on") を使用することです。次に、最初に図を描画し、次にループでプロットを更新します。ループ内では、キャンバスを描画し、ウィンドウが他のイベント (マウス操作など) を処理するために少し一時停止する必要があります。この一時停止がないと、ウィンドウがフリーズします。最後に、plt.waitforbuttonpress()
アニメーションが終了した後もウィンドウを開いたままにするために を呼び出します。
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
fig, ax = plt.subplots()
x, y = [],[]
sc = ax.scatter(x,y)
plt.xlim(0,10)
plt.ylim(0,10)
plt.draw()
for i in range(1000):
x.append(np.random.rand(1)*10)
y.append(np.random.rand(1)*10)
sc.set_offsets(np.c_[x,y])
fig.canvas.draw_idle()
plt.pause(0.1)
plt.waitforbuttonpress()
(b)使用FuncAnimation
上記の多くは、以下を使用して自動化できます。matplotlib.animation.FuncAnimation
FuncAnimation はループと再描画を処理し、animate()
指定された時間間隔で関数 (この場合は ) を継続的に呼び出します。アニメーションはplt.show()
が呼び出された 1 回だけ開始され、プロット ウィンドウのイベント ループで自動的に実行されます。
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
fig, ax = plt.subplots()
x, y = [],[]
sc = ax.scatter(x,y)
plt.xlim(0,10)
plt.ylim(0,10)
def animate(i):
x.append(np.random.rand(1)*10)
y.append(np.random.rand(1)*10)
sc.set_offsets(np.c_[x,y])
ani = matplotlib.animation.FuncAnimation(fig, animate,
frames=2, interval=100, repeat=True)
plt.show()