如何使用Seaborn热力图制作Jupyter HTML-Matplotlib动画?

3

我试图在jupyter中通过seaborn热力图使HTML(anim.to_html5_video)动画生效。

  • 首先,我从文档中获取了可行的示例,并制作了“纯matplotlib” image map animated example,它能够工作,但存在小问题(动画单元格中的“寄生输出”)
  • 然后,我试图让它与seaborn.heatmap一起工作...但失败了。动画看起来像是“无限镜子”——显然matplotlib轴/绘图组合有问题,但我无法解决。

常见的初始化单元格:

import pandas as pd
import seaborn as sns
import numpy as np
%matplotlib inline
#%matplotlib notebook # Tried both, not needed for animation.
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML

动画可以工作,但是存在“不想要的静态输出图像”:
fig, ax = plt.subplots()
nx = 50
ny = 50

line2d, = ax.plot([], [], lw=2)

def init():
    line2d.set_data([], [])
    ax.imshow(np.zeros((nx, ny)))
    return (line2d,)

def animate(i):
    data = np.random.rand(nx, ny)
    ax.set_title('i: ' + str(i))    
    ax.imshow(data)
    return (line2d,)

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=10, interval=1000, blit=False)

HTML(anim.to_html5_video())

所以,我的Jupyter设置(软件包,ffmpeg等)看起来都没问题。

但是,我不知道如何使用seaborn.heatmap:

fig, ax = plt.subplots()
nx = 50
ny = 50

line2d, = ax.plot([], [], lw=2)

ax_global = ax

def init_heatmap():
    line2d.set_data([], [])
    sns.heatmap(np.zeros((nx, ny)), ax=ax_global)
    return (line2d,)


def animate_heatmap(i):
    data = np.random.rand(nx, ny)
    sns.heatmap(data, ax=ax_global)
    ax.set_title('Frame: ' + str(i))    

    return (line2d,)

anim = animation.FuncAnimation(fig, animate_heatmap, init_func=init_heatmap,
                              frames=10, interval=1000, blit=True)

HTML(anim.to_html5_video())    

两个样本都已准备好在Github上测试

当然,我希望看到随机地图和“稳定的热轴”动画,但是得到了这个https://vimeo.com/298786185/

1个回答

3
你可以切换“色条”。从Seaborn.heatmap 文档,你需要将sns.heatmap(data, ax=ax_global)更改为sns.heatmap(data, ax=ax_global, cbar=False),并在init_heatmap()内执行相同操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接