1

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?

enter image description here

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...

Elias Strehle
  • 1,722
  • 1
  • 21
  • 34

1 Answers1

5

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()
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677