如何在Matplotlib中绘制动画矩阵

时间:2018-08-29 00:22:51

标签: python animation matplotlib

我需要在视觉上逐步执行一些数值计算算法,如下图:(gif)

Matrix animation Font

如何用matplotlib制作此动画?有什么办法可以直观地呈现这些过渡?作为矩阵的变换,求和,换位,使用循环并表示转换等。 我的目标不是使用图形,而是使用相同的矩阵表示。这是为了便于理解算法。

2 个答案:

答案 0 :(得分:2)

由于可以使用foreach轻松绘制矩阵,因此可以使用imshow绘制创建这样的表格,并根据当前动画步骤调整数据。

imshow

enter image description here

答案 1 :(得分:0)

此示例在Jupyter笔记本中设置动画内联。我想可能还有一种导出为gif的方法,但是到目前为止我还没有研究过。

无论如何,首先要做的就是设置表格。我从Export a Pandas dataframe as a table image大量借用了render_mpl_table代码。

此问题的(适应)版本为:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import HTML
import six

width = 8
data = pd.DataFrame([[0]*width,
                     [0, *np.random.randint(95,105,size=width-2), 0],
                     [0, *np.random.randint(95,105,size=width-2), 0],
                     [0, *np.random.randint(95,105,size=width-2), 0]])

def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,
                     row_color="w", edge_color="black", bbox=[0, 0, 1, 1],
                     ax=None, col_labels=data.columns, 
                     highlight_color="mediumpurple",
                     highlights=[], **kwargs):
    if ax is None:
        size = (np.array(data.shape[::-1]) + np.array([0, 1])) *
                np.array([col_width, row_height])
        fig, ax = plt.subplots(figsize=size)
        ax.axis('off')

    mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=col_labels,
                         **kwargs)

    mpl_table.auto_set_font_size(False)
    mpl_table.set_fontsize(font_size)

    for k, cell in six.iteritems(mpl_table._cells):
        cell.set_edgecolor(edge_color)
        if k in highlights:
            cell.set_facecolor(highlight_color)
        elif data.iat[k] > 0:
            cell.set_facecolor("lightblue")
        else:
            cell.set_facecolor(row_color)
    return fig, ax, mpl_table

fig, ax, mpl_table = render_mpl_table(data, col_width=2.0, col_labels=None,
                                  highlights=[(0,2),(0,3),(1,2),(1,3)])

在这种情况下,要用不同颜色突出显示的单元格由指定行和列的元组数组给出。

对于动画,我们需要设置一个函数来绘制具有不同亮点的表格:

def update_table(i, *args, **kwargs):
    r = i//(width-1)
    c = i%(width-1)
    highlights=[(r,c),(r,c+1),(r+1,c),(r+1,c+1)]
    for k, cell in six.iteritems(mpl_table._cells):
        cell.set_edgecolor("black")
        if k in highlights:
            cell.set_facecolor("mediumpurple")
        elif data.iat[k] > 0:
            cell.set_facecolor("lightblue")
        else:
            cell.set_facecolor("white")
    return (mpl_table,)

这将强制更新表中所有单元格的颜色。 highlights数组是基于当前帧计算的。在此示例中,表格的宽度和高度都是硬编码的,但是根据输入数据的形状进行更改并不难。

我们基于现有的无花果和更新功能创建动画:

a = animation.FuncAnimation(fig, update_table, (width-1)*3,
                               interval=750, blit=True)

最后,我们在笔记本中内联显示它:

HTML(a.to_jshtml())

我将其放在github上的笔记本中,请参阅https://github.com/gurudave/so_examples/blob/master/mpl_animation.ipynb

希望这足以使您朝正确的方向前进!

相关问题