【问题标题】:Not able to plot real time graph using matplotlib无法使用 matplotlib 绘制实时图形
【发布时间】:2017-07-14 19:34:10
【问题描述】:

我在网上搜索的帮助下编写了以下代码。我的目的是在 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轴的范围不断变化,图形不会出现在图中。

【问题讨论】:

    标签: python animation matplotlib real-time


    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 2023-02-09
      • 2015-06-20
      • 2015-04-24
      • 2017-06-30
      • 2020-09-17
      • 2016-08-17
      • 1970-01-01
      • 2016-04-03
      相关资源
      最近更新 更多