首页 > 解决方案 > 使用 matplotlib 可视化一组数组

问题描述

我想使用 matplotlib 可视化一组数组超时(中间有一些暂停)。到目前为止,我所拥有的是一个数组的可视化,但我不知道如何使它像动画一样。这是我目前拥有的代码,它创建了一个数组列表并成功地可视化了列表中的第一个数组。

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
plt.style.use('classic')

a = []
for i in xrange(5):
    temp = np.zeros((5,5))
    temp[i, i] = 10
    a.append(temp)

fig, ax = plt.subplots(5, 5, figsize=(5, 5))
fig.subplots_adjust(hspace=0, wspace=0)

for i in range(5):
    for j in range(5):
        ax[i, j].xaxis.set_major_locator(plt.NullLocator())
        ax[i, j].yaxis.set_major_locator(plt.NullLocator())
        if a[0][i,j] == 10:
            ax[i, j].imshow(Image.open('A.png'), cmap="bone")
        else:
            ax[i, j].imshow(Image.open('B.png'), cmap="bone")

plt.show()

如何像动画一样可视化列表的所有数组?

标签: pythonanimationmatplotlib

解决方案


您需要导入动画模块并定义一个函数来更改帧以显示您捕获的每个图像。

from matplotlib.animation import FuncAnimation

    def update(i):
        label = 'timestep {0}'.format(i)
        //Insert the data the frame here Eg:ax.imgshow(Image.open('A.png'), cmap="bone")
        ax.set_xlabel(label)
        return line, ax

    FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200)

    plt.show()

您可以按照这个方便的指南进行操作:

https://eli.thegreenplace.net/2016/drawing-animated-gifs-with-matplotlib/


推荐阅读