首页 文章

使用Jupyter Notebook中的Matplotlib为3D矩阵设置动画

提问于
浏览
0

我有一个形状的3D矩阵(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()

将显示此动画的第1个'frame' . 我想在Jupyter笔记本中也有这个显示器 . 我目前正在关注内联笔记本动画的this教程显示为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())

但无论我尝试什么,我都会遇到各种各样的错误,大多与行 im, = ax.imshow([]) 有关 .

任何帮助赞赏!

1 回答

  • 1

    几个问题:

    • 你有很多缺少的进口 .

    • numpy.random.random 将元组作为输入,而不是3个参数

    • imshow 需要一个数组作为输入,而不是一个空列表 .

    • imshow 返回 AxesImage ,无法解压缩 . 因此在作业上没有 , .

    • .set_data() 期望数据,而不是framenumber作为输入 .

    完整代码:

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

相关问题