首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用matplotlib.animation.FuncAnimation一次仅显示一帧

使用matplotlib.animation.FuncAnimation一次仅显示一帧
EN

Stack Overflow用户
提问于 2020-11-02 10:26:19
回答 1查看 306关注 0票数 0

我有一些类似于下面的代码

代码语言:javascript
复制
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层?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-02 10:39:57

您只需要为每个帧使用ax.clear()

代码语言:javascript
复制
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')

这段代码产生

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64639071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档