Python 无法使用matplotlib绘制实时图形

Python 无法使用matplotlib绘制实时图形,python,animation,matplotlib,real-time,Python,Animation,Matplotlib,Real Time,我在在线搜索的帮助下编写了以下代码。我的目的是得到一个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轴上有一些随机生成的值

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轴的范围在不断变化,图形不会出现在图中。

问题是您从未更新
xvar
yvar
。您可以通过将列表的定义移到
动画的定义之外来实现这一点

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