带有固定窗口的python动态图

时间:2019-11-29 19:58:49

标签: python matplotlib

我正在尝试在python中构造一个实时图形以在具有固定绘图窗口的图形中绘制随机数 绘图窗口的宽度为20个样本。对于第21个样本,第一个样本将从右侧消失。这是我的代码。无法弄清楚为什么不绘图。

import random 
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
#creating a subplot 
ax1 = fig.add_subplot(1,1,1)
xs = []
ys = []
iter = 0
def animate(i,xs,ys,iter):
    while True:
        iter = iter+1
        xs.append(iter)
        ys.append(round(random.uniform(-120,20),2))
#I want only 20 data points on the plot i.e the plot window will be only showing 20 samples at a time 
        x = xs[-20:]
        y = ys[-20:]
        ax1.clear()
        ax1.plot(x, y)
        ax1.set_ylim([-120,20])
        plt.xlabel('Value')
        plt.ylabel('Time')
        plt.title('Live Graph')
        time.sleep(1)   

ani = animation.FuncAnimation(fig, animate, fargs = (xs,ys,iter), interval=1000) 
plt.show()

1 个答案:

答案 0 :(得分:2)

签出documentation for FuncAnimation

第二个参数是针对每个连续帧重复调用的函数,每次调用都会更新图形。您的函数animate是一个无限循环,因此执行线程永远不会返回到FuncAnimation。尝试这样的方法作为起点:

import random 
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
xs = []
ys = []
line, = ax1.plot(xs, ys)
plt.xlabel('Value')
plt.ylabel('Time')
plt.title('Live Graph')

def animate(frame, xs, ys):
    xs.append(frame)
    ys.append(round(random.uniform(-120,20),2))
    x = xs[-20:]
    y = ys[-20:]
    line.set_xdata(x)
    line.set_ydata(y)
    ax1.set_xlim(min(x)-1, max(x)+1)
    ax1.set_ylim(min(y)-1, max(y)+1)
    ax1.set_xticks(list(range(min(x), max(x)+1)))
    return line

ani = animation.FuncAnimation(fig, animate, fargs = (xs,ys), interval=100) 
plt.show()