简体   繁体   中英

Plot a rolling window with Matplotlib

I want to plot a time series in a while loop as a rolling window: The graph should always show the 10 most recent observations.

My idea was to use a deque object with maxlen=10 and plot it in every step. To my great surprise the plot appends new values to the old plot; apparently it remembers values that are no longer inside the deque? Why is that and how can I switch it off?

在此处输入图像描述

This is a minimal example of what I am trying to do. The plotting part is based on this post (although plt.ion() did not change anything for me, so I left it out):

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)

I also tried to use Matplotlib's animation functions instead, but could not figure out how to do that in an infinite while loop...

Nowadays, it's much easier (and offers much better performance) to use the animation module than to use multiple calls to 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM