首页 > 解决方案 > 具有固定窗口的python中的实时图

问题描述

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

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()

标签: pythonmatplotlib

解决方案


查看. _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()

推荐阅读