seaborn动画热图/相关矩阵

时间:2015-11-16 19:14:38

标签: python animation matplotlib heatmap seaborn

我是python的新手(来自matlab)。作为一个项目,我试图创建一个随时间变化的相关矩阵的动画图。为了让情节变得美好,我正在尝试海盗。我很难完成动画制作(在mac上遇到matplotlib后端问题),但现在使用来自网络的代码可以使用非常基本的动画:

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在次要情节上工作并且使这些动画变得更加困难。我得到的最好的东西是一种递归情节,其中seaborn.heatmaps被绘制在彼此之上。此外,im.set_data方法不可用。 任何建议都非常感谢。 非常感谢你。

最好,拉尔夫。

4 个答案:

答案 0 :(得分:3)

好点,mwaskom(感谢sns中的所有工作!) - 这就是我被困住的地方。我用seaborn.heatmap替换了plt.imshow(使用set_data生成数据)。

fig = plt.figure()
data = np.random.rand(nx, ny)
sns.heatmap(data, vmax=.8, square=True)

def init():
      sns.heatmap(np.zeros((nx, ny)), vmax=.8, square=True)

def animate(i):
    data = np.random.rand(nx, ny)
    sns.heatmap(data, vmax=.8, square=True)

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=20, repeat = False)

这创造了我挣扎的递归情节。感谢您的帮助,使绘图更漂亮,希望很快也更容易! 最好的,拉尔夫。

答案 1 :(得分:0)

这是一个完整的示例(已通过Matplotlib 3.0.3测试)。

import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns


def animate_heat_map():
    fig = plt.figure()

    nx = ny = 20
    data = np.random.rand(nx, ny)
    ax = sns.heatmap(data, vmin=0, vmax=1)

    def init():
        plt.clf()
        ax = sns.heatmap(data, vmin=0, vmax=1)

    def animate(i):
        plt.clf()
        data = np.random.rand(nx, ny)
        ax = sns.heatmap(data, vmin=0, vmax=1)

    anim = animation.FuncAnimation(fig, animate, init_func=init, interval=1000)

    plt.show()


if __name__ == "__main__":
    animate_heat_map()

答案 2 :(得分:0)

基于r schmaelzle的答案,我用注释创建了动画的Seaborn热图。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import animation


class Heatmap:

    def __init__(self):
        self.fig, self.ax = plt.subplots()
        self.anim = None

    def animate(self):
        def init():
            sns.heatmap(np.zeros((10, 10)), vmax=.8, ax=self.ax)

        def animate(i):
            self.ax.texts = []
            sns.heatmap(np.random.rand(10, 10), annot=True, vmax=.8, cbar=False, ax=self.ax)

        self.anim = animation.FuncAnimation(self.fig, animate, init_func=init, frames=20, repeat=False)

if __name__ == '__main__':
    hm = Heatmap()
    hm.animate()

更新注释的技巧是使空ax.texts = []

我希望它将对他人有所帮助! :)

答案 3 :(得分:0)

除了你上面的回答,我想从数据框列表中做到这一点并保存为 gif。因此,使用您的代码和 Serenity 对 Matplotlib animation iterating over list of pandas dataframes

的回答
const {users, setUsers, horizontalDiscussion, setHorizontalDiscussion} = useContext(UserContext);

谢谢!!!

相关问题