0

我有一些类似的代码

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 图层?

4

1 回答 1

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')

此代码产生

图

于 2020-11-02T02:39:56.613 回答