Animating a kdeplot python

Viewed 43

Im trying to annimate a kdeplot in python.

The idea is to evaluate actions over time. The script below almost works as planned, but instead of updating the plot, it overlaps the plots and becomes very slow after a few runs.

So I can see that my problem might be that i dont really understand the animate func and have now becom very lost in trying to understand the problem.

So i hope that soembody can see the problem and help me.

import numpy as np
from matplotlib import animation
import matplotlib.pyplot as plt
import pandas as pd
import cmasher as cmr
from mplsoccer import VerticalPitch

df = pd.DataFrame(np.random.randint(0,100,size=(1000, 2)), columns=list('xy'))

#%%

pitch_dark = VerticalPitch(line_color='#cfcfcf', line_zorder=2, pitch_color='#122c3d')
fig, ax = pitch_dark.draw()
#kdeplot_dark = pitch_dark.kdeplot([], [], ax=ax, cmap=cmr.voltage, shade=True, levels=100)

def init():
    kdeplot_dark = pitch_dark.kdeplot(0,0, ax=ax, cmap=cmr.voltage, shade=True, levels=100)

def animate(i):
    x = df.x.iloc[i:i+20]
    y = df.y.iloc[i:i+20]
    kdeplot_dark = pitch_dark.kdeplot(x,y, ax=ax, cmap=cmr.voltage, shade=True, levels=100)

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

plt.show()
0 Answers
Related