如何为Seaborn的热图或相关矩阵制作动画? [英] How to animate a seaborn's heatmap or correlation matrix?
问题描述
我对python相对较新(来自Matlab).作为一个项目,我试图创建一个随时间变化的相关矩阵动画图.为了使情节变得美好,我正在尝试seaborn.我很难使动画完全完成(在Mac上Matplotlib后端存在问题),但是现在可以使用网上的以下代码来制作非常基本的动画:
I am relatively new to python (coming from Matlab). As one project, I am trying to create an animated plot of a correlation matrix over time. To make the plots nice, I am trying seaborn. I struggled to get the animation done at all (having issues with Matplotlib backend on a mac), but a very basic animation now works using this code from the web:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
nx = 50
ny = 50
fig = plt.figure()
data = np.random.rand(nx, ny)
im = plt.imshow(data)
def init():
im.set_data(np.zeros((nx, ny)))
def animate(i):
#xi = i // ny
#yi = i % ny
data = np.random.rand(nx, ny)
im.set_data(data)
return im
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=50, repeat = False)
现在,我正在尝试使其适应 seaborn
,但没有成功.似乎在子图上进行深造并制作动画效果要困难得多.我曾经获得的最好的东西是一种递归图,其中 seaborn.heatmaps
相互绘制.此外, im.set_data
方法也不可用.
Now, I was trying to adapt this to seaborn
, but did not succeed. It seems that seaborn works on subplots and to animate these was far harder. The best thing I got once was a kind of recursive plot, where seaborn.heatmaps
were plotted on top of each other. Also, the im.set_data
method was not available.
任何建议都将受到高度赞赏.
Any suggestions are highly appreciated.
推荐答案
我用替换了
. plt.imshow
(通过 set_data
广播数据无效)seaborn.heatmap
I replaced plt.imshow
(casting data via set_data
didn't work) with seaborn.heatmap
.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import animation
fig = plt.figure()
data = np.random.rand(10, 10)
sns.heatmap(data, vmax=.8, square=True)
def init():
sns.heatmap(np.zeros((10, 10)), vmax=.8, square=True, cbar=False)
def animate(i):
data = np.random.rand(10, 10)
sns.heatmap(data, vmax=.8, square=True, cbar=False)
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=20, repeat = False)
这将创建我遇到的递归图.
This creates the recursive plot I struggled with.
这篇关于如何为Seaborn的热图或相关矩阵制作动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!