python - 在 Jupyter Notebook 中使用 Matplotlib 对 3D 矩阵进行动画处理
问题描述
我有一个形状为 (100,50,50) 的 3D 矩阵,例如
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 中也有这个显示。我目前正在关注本教程,将内联笔记本动画显示为 html 视频,但我不知道如何用二维数组的切片替换 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([])
任何帮助表示赞赏!
解决方案
几个问题:
- 你有很多缺失的进口。
numpy.random.random
将一个元组作为输入,而不是 3 个参数imshow
需要一个数组作为输入,而不是一个空列表。imshow
返回一个AxesImage
,它不能被解包。因此没有,
分配。.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())