0

I've got some code similar to this

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

I'm trying to show only one frame at a time, but the code that I have written uses two ax.hexbin() calls and I have to remove one of them in order to show the correct graph. Is there a way to show one hexbin layer at a time using FuncAnimation?

Ethan
  • 534
  • 5
  • 21

1 Answers1

1

You only need ax.clear() for each frame

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

this code produces

fig

meTchaikovsky
  • 7,478
  • 2
  • 15
  • 34
  • When I try this I get a `TypeError: 'AxesSubplot' object is not iterable` error. Any ideas how I can fix this? – Ethan Nov 02 '20 at 02:48
  • @Ethan I don't know, the code in my post just runs perfectly in jupyter notebook. – meTchaikovsky Nov 02 '20 at 02:50
  • I fixed the error above but the funcAnimation object that it creates is blank – Ethan Nov 02 '20 at 03:03
  • @Ethan I can't tell what really causes the problem in your code. Can you run my code in a fresh session? Since my code really works on my mac. – meTchaikovsky Nov 02 '20 at 03:05
  • I had to mess with a few other things, but that ended up working out! Thanks! – Ethan Nov 02 '20 at 05:08
  • since the animate function now returns ax instead of hexbin, there was some formatting I had to do. But it worked! – Ethan Nov 02 '20 at 05:08