无法使用 matplotlib 绘制实时图形

Not able to plot real time graph using matplotlib

我借助网上的搜索编写了如下代码。我的目的是获得一个实时图表,其中 x 轴为时间,y 轴为一些随机生成的值

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    xar = []
    yar = []
    x,y = time.time(), np.random.rand()
    xar.append(x)
    yar.append(y)
    ax1.clear()
    ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show() 

上面的代码我只是看到y轴的范围在不断变化,图中不会出现图形。

问题是您从未更新 xvaryvar。您可以通过将列表的定义移到 animate.

的定义之外来做到这一点
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
xar = []
yar = []

def animate(i):
    x,y = time.time(), np.random.rand()
    xar.append(x)
    yar.append(y)
    ax1.clear()
    ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()