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

Ric*_*all 3 python matplotlib jupyter-notebook

我有一个形状为 (100,50,50) 的 3D 矩阵,例如

import numpy as np
data = np.random.random(100,50,50)
Run Code Online (Sandbox Code Playgroud)

我想创建一个动画,将每个大小为 (50,50) 的 2D 切片显示为热图或imshow

例如:

import matplotlib.pyplot as plt

plt.imshow(data[0,:,:])
plt.show()
Run Code Online (Sandbox Code Playgroud)

将显示该动画的第一个“帧”。我还想在 Jupyter Notebook 中显示此内容。我目前正在按照教程将内联笔记本动画显示为 html 视频,但我不知道如何用 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())
Run Code Online (Sandbox Code Playgroud)

但无论我尝试什么,我都会遇到各种错误,主要与该行相关im, = ax.imshow([])

任何帮助表示赞赏!

Imp*_*est 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())
Run Code Online (Sandbox Code Playgroud)