【问题标题】:Show only one frame at a time using matplotlib.animation.FuncAnimation使用 matplotlib.animation.FuncAnimation 一次只显示一帧
【发布时间】:2023-03-03 06:19:26
【问题描述】:

我有一些类似的代码

from matplotlib import animation
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

def animate(i):
    x0,y0 = np.random.random(size=(2,))*4-2
    x = np.random.normal(loc=x0, size=(1000,))
    y = np.random.normal(loc=y0, size=(1000,))

    for layer in prevlayers:
        layer.remove()
    prevlayers[:] = []

    hexlayer = ax.hexbin(x,y, gridsize=10, alpha=0.5)
    # the following line is needed in my code
    hexlayer.remove()
    prevlayers.append(hexlayer)
    return hexlayer,

prevlayers = []
ani = animation.FuncAnimation(fig, animate, frames=12)
ani.save('teste.gif', writer='PillowWriter')

我试图一次只显示一帧,但我编写的代码使用了两个 ax.hexbin() 调用,我必须删除其中一个才能显示正确的图形。有没有办法使用 FuncAnimation 一次显示一个 hexbin 图层?

【问题讨论】:

    标签: python matplotlib matplotlib-basemap matplotlib-animation


    【解决方案1】:

    每一帧你只需要ax.clear()

    from matplotlib import animation
    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()
    
    def animate(i):
        
        ax.clear()
        x0,y0 = np.random.random(size=(2,))*4-2
        x = np.random.normal(loc=x0, size=(1000,))
        y = np.random.normal(loc=y0, size=(1000,))
    
        hexlayer = ax.hexbin(x,y, gridsize=10, alpha=0.5)
        
        return ax 
    
    ani = animation.FuncAnimation(fig, animate, frames=12)
    ani.save('teste.gif', writer='PillowWriter')
    

    这段代码产生

    【讨论】:

    • 当我尝试这个时,我得到一个TypeError: 'AxesSubplot' object is not iterable 错误。有什么想法可以解决这个问题吗?
    • @Ethan 我不知道,我帖子中的代码在 jupyter notebook 中完美运行。
    • 我修复了上面的错误,但是它创建的 funcAnimation 对象是空白的
    • @Ethan 我不知道是什么真正导致了代码中的问题。你能在新的会话中运行我的代码吗?因为我的代码真的可以在我的 mac 上运行。
    • 我不得不处理其他一些事情,但最终解决了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2011-01-23
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多