Animated heatmap with seaborn and matplotlib

Hello everyone !

I’m trying to animate a heatmap for data visualization.
(Just to clarify, I am a beginner in coding)

The heatmap is generated from a matrix where cells situated at the center of the map take a +1 value at each iteration. I don’t use numpy for the matrix but comprehension list. Heatmaps are generated with Seaborn module.

The heatmap is generated correctly and the matrix values change well. However, the animation does not start. I get a frozen image as if I had only generated a heat map without animation.

Here is the code :

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

#Definition of the initial matrix
def random_bed(p, n):
… states=[[0]*n for _ in range(n)]
… A=[(3,3),(3,4),(3,5),(3,6),(4,3),(4,4),(4,5),(4,6),(5,3),(5,4),(5,5),(5,6),(6,3),(6,4),(6,5),(6,6)]
… for (i,j) in A:
… states[i][j]=1
… return states

p=1
n=10
states=random_bed(p, n)

#function which aims to animate the matrix and increase the values of the center
def animate(i):
… data = states
… A=[(3,3),(3,4),(3,5),(3,6),(4,3),(4,4),(4,5),(4,6),(5,3),(5,4),(5,5),(5,6),(6,3),(6,4),(6,5),(6,6)]
… for (i,j) in A:
… states[i][j]=states[i][j]+1
… return states
… sns.heatmap(data, vmax=100)

fig = plt.figure()
sns.heatmap(states)
anim = animation.FuncAnimation(fig, animate, frames=20, repeat=False)
plt.show()

Here is an example of the output (with no animation):

image

Does anyone have an idea of my mistake?

Thank you very much for taking the time to read me.

Have a great day !

Axel MEYER

So, basically you setup your figure, and then you’d want to use animate to modify it. I’m new to using matlab and never used seaborn, but from a basic programming perspecive I believe you just want your animation function to make changes, then replot.

Right now your animate function just returns the value of states, but nothing requests a replot (your new heatmap occurs after you return so it doesn’t execute.

I made your animation function into this:

def animate(i):
    print("animation running...")
    A=[(3,3),(3,4),(3,5),(3,6),(4,3),(4,4),(4,5),(4,6),(5,3),(5,4),(5,5),(5,6),(6,3),(6,4),(6,5),(6,6)]
    for (i,j) in A:
        states[i][j]=states[i][j]+1

    fig.clear()
    sns.heatmap(states, vmax=30)

Is that basically what you were wanting?

1 Like

Yes it’s working ! Thank you very much !!

Here is the final code:

def animate(i):
    print("animation running...")
    A=[(3,3),(3,4),(3,5),(3,6),(4,3),(4,4),(4,5),(4,6),(5,3),(5,4),(5,5),(5,6),(6,3),(6,4),(6,5),(6,6)]
    for (i,j) in A:
        states[i][j]=states[i][j]+1

    fig.clear()
    sns.heatmap(states, vmax=30)

fig=plt.figure()
anim=animation.FuncAnimation(fig, animate, frames=20, repeat=False)
plt.show()

Thank you for these rich explanations ! :slight_smile:

Have a great day !

Axel MEYER