使用matplotlib无法绘制实时图表。

3
我借助在线搜索编写了以下代码。我在这里的意图是获得一个实时图表,其中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轴范围不断变化,图形不会出现在图中。

1个回答

1
问题在于您从未更新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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接