Skip to content Skip to sidebar Skip to footer

Animate A 3d Matrix With Matplotlib In Jupyter Notebook

I have a 3D matrix of shape (100,50,50), e.g. import numpy as np data = np.random.random(100,50,50) And I want to create an animation that shows each of the 2D slices of size (50,

Solution 1:

Several issues:

  1. You have a lot of missing imports.
  2. numpy.random.random takes a tuple as input, not 3 arguments
  3. imshow needs an array as input, not an empty list.
  4. imshow returns an AxesImage, which cannot be unpacked. Hence no , on the assignment.
  5. .set_data() expects the data, not the framenumber as input.

Complete code:

from IPython.display import HTML
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

data = np.random.rand(100,50,50)

fig, ax = plt.subplots()

ax.set_xlim((0, 50))
ax.set_ylim((0, 50))

im = ax.imshow(data[0,:,:])

def init():
    im.set_data(data[0,:,:])
    return (im,)

# animation function. This is called sequentially
def animate(i):
    data_slice = data[i,:,:]
    im.set_data(data_slice)
    return (im,)

# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

HTML(anim.to_html5_video())

Post a Comment for "Animate A 3d Matrix With Matplotlib In Jupyter Notebook"