【问题标题】:How to use NumPy arrays while Plotting Live Data in Real-Time?如何在实时绘制实时数据时使用 NumPy 数组?
【发布时间】:2021-07-24 05:45:07
【问题描述】:

如何在实时构建图中正确使用 numpy 数组,我的意思是,如果我使用这些数组,我会将值推送到其中,除了从 (0;0) 开始的线和每次都指向当前绘图点的线外,一切都很好,换句话说,第一端保持稳定,但第二端改变了它的位置。该怎么办?另外我不明白如何在动画()处通过引用传递参数。

s = '.........................................................................................'+
string.ascii_uppercase
letters = [s[randint(0, len(s)-1)] for _ in range(5000)] #массив букв
time    = [i for i in range(5000)]
example = [randint(0, 100) for _ in range(5000)]

t = count()
frequency = 0
time_x = np.zeros(len(time))
key_y = np.zeros(len(time))

cnt = 0

def animate(i):
    global cnt
    time_x[cnt] = time[cnt]
    key_y[cnt] = example[cnt]

    print (time_x[cnt], key_y[cnt])
    plt.cla()
    plt.plot(time_x, key_y)
    cnt += 1

ani = FuncAnimation(plt.gcf(), animate, interval=3000)

plt.show()

【问题讨论】:

    标签: python numpy matplotlib animation plot


    【解决方案1】:

    在您执行plt.plot(time_x, key_y) 的行中,因为time_xkey_y 被实例化为一个零数组,所以总是有从您最后生成的点到[0, 0] 位置的线(直到你生成cnt=4999的点)。

    例如如果cnt=2 在您的数据生成循环中,它可能看起来像:

    time_x = [  0.0, 1.0,  2.0, 0.0, 0.0, 0.0, ...]
    key_y  = [100.0, 1.0, 52.0, 0.0, 0.0, 0.0, ...]
    

    这意味着您还绘制了很多零!

    我认为您只想绘制到cnt(您已为其生成数据),即plt.plot(time_x[:cnt], key_y[:cnt]),或者在您的示例中:

    import numpy as np
    from random import randint
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    
    s = '.........................................................................................'
    letters = [s[randint(0, len(s)-1)] for _ in range(5000)]
    time = [i for i in range(5000)]
    example = [randint(0, 100) for _ in range(5000)]
    
    time_x = np.zeros(len(time))
    key_y = np.zeros(len(time))
    
    def animate(cnt, param_1, param_2):
        time_x[cnt] = time[cnt]
        key_y[cnt] = example[cnt]
        print(cnt, time_x[cnt], key_y[cnt], f'Extra params: {param_1}, {param_2}')
        plt.cla()
        plt.plot(time_x[:cnt], key_y[:cnt])
    
    
    extra_params = ('p_1', 'p_2')
    
    ani = FuncAnimation(plt.gcf(), animate, interval=3000, fargs=extra_params)
    plt.show()
    

    传递给 animate (i) 的第一个参数已经是 global cnt 曾经在你的原始代码中做,所以你可以替换它。如果您想传递特定的cnt 值,如in the docs 建议的那样,您可以尝试添加frames 参数。

    如果要传入其他参数,可以使用fargs 参数。您可以将额外数据作为元组传递,如extra_params 所示。

    如果您想做更复杂的事情,我会使用 python 类来存储状态,如SO post 所示。

    【讨论】:

    • 谢谢,它有帮助。是否可以通过链接将cnt传递给animation()?
    • @MrFilonxik 我已经编辑了我的答案,如果你的意思是别的,请告诉我!
    猜你喜欢
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2021-09-07
    • 2015-09-15
    • 1970-01-01
    • 2016-06-16
    相关资源
    最近更新 更多