[英]Plot a rolling window with Matplotlib
我想在while
循環中將時間序列繪制為滾動窗口:圖表應始終顯示 10 個最近的觀察結果。
我的想法是使用maxlen=10
的雙端隊列對象並在每一步中繪制它。 令我非常驚訝的是,該情節將新值附加到舊情節; 顯然它記得不再在雙端隊列中的值? 為什么會這樣,我該如何關閉它?
這是我正在嘗試做的一個最小示例。 繪圖部分基於這篇文章(盡管plt.ion()
對我沒有任何改變,所以我把它省略了):
from collections import deque
import matplotlib.pyplot as plt
import numpy as np
x = 0
data = deque(maxlen=10)
while True:
x += np.abs(np.random.randn())
y = np.random.randn()
data.append((x, y))
plt.plot(*zip(*data), c='black')
plt.pause(0.1)
我也嘗試使用 Matplotlib 的動畫函數來代替,但無法弄清楚如何while
無限循環中做到這一點......
如今,使用animation
模塊比多次調用plt.plot
更容易(並且提供更好的性能):
from collections import deque
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
def animate(i):
global x
x += np.abs(np.random.randn())
y = np.random.randn()
data.append((x, y))
ax.relim()
ax.autoscale_view()
line.set_data(*zip(*data))
fig, ax = plt.subplots()
x = 0
y = np.random.randn()
data = deque([(x, y)], maxlen=10)
line, = plt.plot(*zip(*data), c='black')
ani = animation.FuncAnimation(fig, animate, interval=100)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.