来自 Pandas DataFrames 字典的动画热图

Animated heatmap from dictionary of Pandas DataFrames

我想从一组数据帧(例如保存在字典中)绘制动画热图,作为 gif 或电影。

例如,假设我有以下 DF 集合。我可以一个接一个地展示所有这些。但我想让它们都以与显示 GIF 相同的方式显示在同一个图中(热图循环)。

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

dataframe_collection = {}

for i in range(5):
    dataframe_collection[i] = pd.DataFrame(np.random.random((5,5)))

    # Here within the same loop just for brevity
    sns.heatmap(dataframe_collection[i])
    plt.show()

最简单的方法是先创建单独的png图像,然后使用ImageMagick等软件将它们转换为动画gif。

创建 png 的示例:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

dataframe_collection = {}
for i in range(5):
    dataframe_collection[i] = pd.DataFrame(np.random.random((5,5)))
    #plt.pcolor(dataframe_collection[i])
    sns.heatmap(dataframe_collection[i])
    plt.gca().set_ylim(0, len(dataframe_collection[i])) #avoiding problem with axes
    plt.axis('off')
    plt.tight_layout()
    plt.savefig(f'dataframe_{i}.png')

安装后 ImageMagick the following shell command creates a gif. If the defaults are not satisfying, use the docs 探索许多选项。

convert.exe -delay 20 -loop 0 dataframe_*.png dataframes.gif

另请参阅 this post 关于在 matplotlib 中创建动画和动画 gif。

请注意,Seaborn 的热图还具有一些特征,例如 sns.heatmap(dataframe_collection[i], annot=True)

如果您无法使用 ImageMagick,您可以通过快速显示单个 png 文件来模拟视频来显示视频。 This and this post contain more explanations and example code. Especially the second part of this answer 看起来很有希望。