【问题标题】:Updating Matplotlib subplots with images in Jupyter/Python 3在 Jupyter/Python 3 中使用图像更新 Matplotlib 子图
【发布时间】:2018-01-15 01:36:22
【问题描述】:

我有一个从外部源修改的函数,它获取图像列表并将它们显示在 Jupyter 笔记本(python 3)内的网格上。

def show_images(images):
    images = np.reshape(images, [images.shape[0], -1])  

    fig = plt.figure(figsize=(28, 28))
    gs = gridspec.GridSpec(28, 28)
    gs.update(wspace=0.05, hspace=0.05)

    for i, img in enumerate(images):
        ax = plt.subplot(gs[i])
        plt.axis('off')
        ax.set_aspect('equal')
        plt.imshow(img.reshape([28, 28]))
    return

这需要许多 mnist 或类似格式的数据数组(因此有 28 个图像大小),并且在机器学习算法的内部经常被调用。每次调用它时,它都会在 Jupyter 窗口中添加另一个图形,所以最后,我有一个长滚动输出。

我想要修改这个函数(或创建一个配套函数),以便它更新现有的图形而不是制作新的图形。理想情况下,它就像一个缓慢演变的动画,其帧速率由循环的速度设置(相对较慢,大约为秒。)

我尝试了各种保存和重新使用图形、网格规范和轴的方法,以及绘制和重新显示这些元素的各种排列,但没有任何效果——要么我没有得到图形输出,或者只有一个不更新的静态图像(但也不会继续添加更多数字。)

【问题讨论】:

  • this question 的答案中给出了在 jupyter 中显示动画的选项。

标签: python-3.x matplotlib jupyter-notebook


【解决方案1】:

一个可能的解决方案是返回gs 并将其传递给show_images 函数。可以修改该函数,以便如果未将 gs 传递给它,则它会创建一个新图形:

类似的东西:

def show_images(images, gs=None):
    images = np.reshape(images, [images.shape[0], -1])  

    if gs is None:
        fig = plt.figure(figsize=(28, 28))
        gs = gridspec.GridSpec(28, 28)
        gs.update(wspace=0.05, hspace=0.05)
    else:
        plt.clf()  # clear figure if one is already present

    for i, img in enumerate(images):
        ax = plt.subplot(gs[i])
        plt.axis('off')
        ax.set_aspect('equal')
        plt.imshow(img.reshape(28, 28))

    return gs

然后调用函数:

# first time calling the function. Don't pass gs argument
gs = show_images(images)

# Many lines of code later...

gs = show_images(images, gs)

【讨论】:

    猜你喜欢
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 2021-06-13
    • 2013-08-25
    • 2015-08-06
    • 2019-01-02
    • 1970-01-01
    相关资源
    最近更新 更多