在Jupyter Notebook中使用Matplotlib制作3D矩阵动画

3

我有一个形状为(100,50,50)的三维矩阵,例如:

import numpy as np
data = np.random.random(100,50,50)

我希望您能够创建一个动画,将大小为(50,50)的2D切片显示为热力图或imshow

例如:

import matplotlib.pyplot as plt

plt.imshow(data[0,:,:])
plt.show()

将会显示此动画的第一帧。我希望在Jupyter Notebook中也能显示。我目前正在按照这篇教程进行内联笔记本动画的显示,但我不知道如何用我的2D数组切片替换1D线性数据。

我知道我需要创建一个图形元素、一个初始化函数和一个动画函数。按照那个例子,我尝试过:

fig, ax = plt.subplots()

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

im, = ax.imshow([])

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

# animation function. This is called sequentially
def animate(i):
    data_slice = data[i,:,:]
    im.set_data(i)
    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())

无论我尝试什么,都会出现各种错误,大多数与此行有关:im, = ax.imshow([])

非常感谢您的帮助!

1个回答

5

几个问题:

  1. 您缺少了很多导入。
  2. numpy.random.random需要一个元组作为输入,而不是3个参数。
  3. imshow需要一个数组作为输入,而不是一个空列表。
  4. imshow返回一个AxesImage,不能被拆开。因此在赋值时没有,
  5. .set_data()期望的是数据,而不是帧编号作为输入。

完整代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接