【问题标题】:matplotlib while loop (matplotlib.animation?)matplotlib while 循环(matplotlib.animation?)
【发布时间】:2016-10-28 21:45:48
【问题描述】:

我正在使用 matplotlib 绘制数据。

我想观察几秒钟内绘制的数据。

当前脚本(如下)已关闭。它关闭现有绘图并制作一个新绘图,其中包括每个 while 循环迭代的一个附加数据点。

如果在循环上方键入“fig=" 和 "ax1=" 语句,我只会得到一个空白图。

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


def animate2(i):

    k=1

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

    while k <=len(i):

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

        ax1.clear
        ax1.plot(i[0:k, 0], i[0:k, 1])

        plt.show()
        time.sleep(1)
        k=k+1

这里是我使用的示例 np 数组:

test_data=np.array([[3, 7],[1, 2],[8, 11],[5, -12],[20, 25], [-3, 30], [2,2], [17, 17]])

animate2(test_data)

另外,如果您认为 matplotlib.animation 会更好,请提供示例!

【问题讨论】:

    标签: python animation matplotlib plot


    【解决方案1】:

    使用matplot.animation。它使用interval=miliseconds 而不是time.sleep()repeat 停止循环。 frames 可以是整数(帧数)或带有数字的列表 - 列表中的每个元素都作为参数 i 发送到函数。

    import numpy as np
    import matplotlib.pyplot as plt 
    import matplotlib.animation as animation
    
    
    def animate2(i):
    
        ax1.clear()
        ax1.plot(test_data[0:i, 0], test_data[0:i, 1])
    
    # ---
    
    test_data=np.array([[3, 7],[1, 2],[8, 11],[5, -12],[20, 25], [-3, 30], [2,2], [17, 17]])
    
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)
    
    # create animation
    animation.FuncAnimation(fig, animate2, frames=range(1, len(test_data)), interval=1000, repeat=False)
    
    # start animation
    plt.show()
    

    您也可以使用fargs=tuplet-with-arguments 将自己的参数发送给函数

    def animate2(i, data):
    
        ax1.clear()
        ax1.plot(data[0:i, 0], data[0:i, 1])
    
    # ---
    
    animation.FuncAnimation(fig, animate2, frames=range(1, len(test_data)), 
                             fargs=(test_data, ), interval=1000)
    

    编辑:

    我使用此代码生成动画 GIF

    (需要安装imagemagickhttps://stackoverflow.com/a/25143651/1832058

    # create animation
    ani = animation.FuncAnimation(fig, animate2, frames=range(1, len(test_data)), interval=1000, repeat=False)
    
    # save animation
    ani.save('animation.gif', writer='imagemagick', fps=1)
    

    得到了这个结果

    【讨论】:

    • 酷@furas,感谢您的帮助!你测试过这个吗?就我而言,它仍然会生成一个空白的白色情节..
    • 我的 python 环境是 Enthought Canopy 包附带的,如果这有什么不同的话
    • 我测试了这段代码。也许你收到了一些错误信息,而他就是你什么都没有得到的原因。
    • 顺便说一句,您可以将print() 放在animate2 和其他地方,以查看执行了哪些部分。
    • 好的,很高兴知道。我一直在 jupyter notebook 中测试东西,但没有看到任何错误。我会继续努力..非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多