简体   繁体   English

使用 Matplotlib 绘制滚动窗口

[英]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.我想在while循环中将时间序列绘制为滚动窗口:图表应始终显示 10 个最近的观察结果。

My idea was to use a deque object with maxlen=10 and plot it in every step.我的想法是使用maxlen=10双端队列对象并在每一步中绘制它。 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):绘图部分基于这篇文章(尽管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)

I also tried to use Matplotlib's animation functions instead, but could not figure out how to do that in an infinite while loop...我也尝试使用 Matplotlib 的动画函数来代替,但无法弄清楚如何while无限循环中做到这一点......

Nowadays, it's much easier (and offers much better performance) to use the animation module than to use multiple calls to plt.plot :如今,使用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.

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