Animating a kdeplot python - python

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()

Related

Trouble animating a 3D plot in python

I'm trying to animate a curve in 3D and am having some trouble. I've successfully animated some things in 2D, so I thought I knew what I was doing. In the code below, I generate x, y, and z values parametrically to be a helix and have verified that I can plot the full curve in 3D. To animate the curve I am trying to begin by plotting only the first two data points and then use FuncAnimation to update the data so that it plots larger portions of the data. But as I said, it is not working for some reason and I have no idea why; all I get is the initial plot with the first two data points. Any help would be appreciated.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
t_max = 10
steps = 100
t = np.linspace(0, t_max, steps)
x = np.cos(t)
y = np.sin(t)
z = 0.1*t
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
line, = ax.plot(x[0:1], y[0:1], z[0:1])
def update(i):
line.set_xdata(x[0:i])
line.set_ydata(y[0:i])
line.set_zdata(z[0:i])
fig.canvas.draw()
ani = animation.FuncAnimation(fig, update, frames=t, interval=25, blit=False)
plt.show()
Okay, I finally got it to work. I had a dumb error (frames=t), but also figured out that you need to set the data in the update function differently. Here is the working code in case anyone is interested.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
t_max = 10
steps = 100
t = np.linspace(0, t_max, steps)
x = np.cos(t)
y = np.sin(t)
z = 0.1*t
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
line, = ax.plot([], [], [], lw=1)
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)
ax.set_zlim(0,1)
plt.show()
def update(i):
line.set_data(x[0:i], y[0:i])
line.set_3d_properties(z[0:i])
return
ani = animation.FuncAnimation(fig, update, frames=100, interval=10, blit=True)
plt.show()

How to add a timer in an animation.FuncAnimation (), using pandas/Geopandas?

I am creating an animation by using GeoPandas and everything is going well but I'd like to include a timer, in order to know the time corresponding to my visualization.
I think the way is by means of set_text, but I think everything is lost in the update done by Geopandas to plot (ax=ax).
So, the instruction time_text is the one that is not working on my code. Please any help/suggestion/idea? Thanks in advance!!
Here the important part of my code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import geopandas as gpd
import pandas as pd
from shapely.geometry import Point
fig = plt.figure()
ax = plt.axes(xlim=(2.5, 7), ylim=(48, 52))
time_text = ax.text(2.8, 50.,"",transform = ax.transAxes, ha="right")
ax.legend()
t=0
bel = gpd.read_file('....')
def init():
global inicio
inicio = bel.plot( ax=ax, color='black', markersize=5)
time_text.set_text("")
return inicio, time_text
data = pd.read_csv('.....')
legend = plt.legend(loc='lower left',prop={'size': 7})
def animate(i):
global inu, iterar, t
t += 1
ax.clear()
inu = bel.plot( ax=ax, color='lightgray', linewidth=1., edgecolor='black')
cond = geo_data[ geo_data['newdate'].dt.minute == i]
iterar = cond.plot(ax=ax,marker='s',color='yellow', markersize=7.,alpha=0.3,label='Max >= 60 Tonne');
legend = plt.legend(loc='lower left',prop={'size': 7})
time_text.set_text("time = "+str(t))
return iterar,inu,time_text
anim = animation.FuncAnimation(fig, animate, init_func=init,frames=60, interval=500, blit=False)
plt.show()

matplotlib artist animation : title or text not changing

I tried using matplotlib's ArtistAnimation. The text and titles of the figure are supposed to change in each frame, but they don't.
I have read tons of posts on similar problems, but I still don't understand what is the solution. The demos don't show updating titles as far as I could find.
If anybody out there knows, I would be grateful!
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
fig =plt.figure()
ims=[]
for iternum in range(4):
plt.title(iternum)
plt.text(iternum,iternum,iternum)
ims.append([plt.scatter(np.random.randint(0,10,5), np.random.randint(0,20,5),marker='+' )])
#plt.cla()
ani = animation.ArtistAnimation(fig, ims, interval=500, blit=False,
repeat_delay=2000)
plt.show()
To animate artists, you have to return a reference to each artists in your ims[] array, including the Text objects.
However it doesn't work for the title, I don't know why. Maybe somebody with a better understanding of the mechanisms involved will be able to enlighten us.
Nevertheless, the title is just a Text object, so we can produce the desired effect using:
fig = plt.figure()
ax = fig.add_subplot(111)
ims=[]
for iternum in range(4):
ttl = plt.text(0.5, 1.01, iternum, horizontalalignment='center', verticalalignment='bottom', transform=ax.transAxes)
txt = plt.text(iternum,iternum,iternum)
ims.append([plt.scatter(np.random.randint(0,10,5), np.random.randint(0,20,5),marker='+' ), ttl, txt])
#plt.cla()
ani = animation.ArtistAnimation(fig, ims, interval=500, blit=False,
repeat_delay=2000)
You need to supply the artists to animate as a list of sequences to the ArtistAnimation. In the code from the question you only supply the scatter, but not the text and title.
Unfortunately the title is also part of the axes and thus will not change even if supplied. So you may use a normal text instead.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
fig, ax = plt.subplots()
ims=[]
for iternum in range(4):
title = plt.text(0.5,1.01,iternum, ha="center",va="bottom",color=np.random.rand(3),
transform=ax.transAxes, fontsize="large")
text = ax.text(iternum,iternum,iternum)
scatter = ax.scatter(np.random.randint(0,10,5), np.random.randint(0,20,5),marker='+')
ims.append([text,scatter,title,])
ani = animation.ArtistAnimation(fig, ims, interval=500, blit=False,
repeat_delay=2000)
plt.show()
You may consider using FuncAnimation instead of ArtistAnimation. This would allow to change the title easily.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
fig, ax = plt.subplots()
ims=[]
text = ax.text(0,0,0)
scatter = ax.scatter(np.random.randint(0,10,5), np.random.randint(0,20,5),marker='+')
def update(iternum):
plt.title(iternum)
text.set_position((iternum, iternum))
text.set_text(str(iternum))
scatter.set_offsets(np.random.randint(0,10,(5,2)))
ani = animation.FuncAnimation(fig, update, frames=4, interval=500, blit=False,
repeat_delay=2000)
plt.show()

Why does the output of animation.FuncAnimation have to be bound to a name? [duplicate]

I am trying to do an animation using the FuncAnimation module, but my code only produces one frame and then stops. It seems like it doesn't realize what it needs to update. Can you help me what went wrong?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.linspace(0,2*np.pi,100)
def animate(i):
PLOT.set_data(x[i], np.sin(x[i]))
print("test")
return PLOT,
fig = plt.figure()
sub = fig.add_subplot(111, xlim=(x[0], x[-1]), ylim=(-1, 1))
PLOT, = sub.plot([],[])
animation.FuncAnimation(fig, animate, frames=len(x), interval=10, blit=True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.linspace(0,2*np.pi,100)
fig = plt.figure()
sub = fig.add_subplot(111, xlim=(x[0], x[-1]), ylim=(-1, 1))
PLOT, = sub.plot([],[])
def animate(i):
PLOT.set_data(x[:i], np.sin(x[:i]))
# print("test")
return PLOT,
ani = animation.FuncAnimation(fig, animate, frames=len(x), interval=10, blit=True)
plt.show()
You need to keep a reference to the animation object around, otherwise it gets garbage collected and it's timer goes away.
There is an open issue to attach a hard-ref to the animation to the underlying Figure object.
As written, your code well only plot a single point which won't be visible, I changed it a bit to draw up to current index

How to embed matplotlib funcAnimation object within PyQT GUI [duplicate]

I am trying to do an animation using the FuncAnimation module, but my code only produces one frame and then stops. It seems like it doesn't realize what it needs to update. Can you help me what went wrong?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.linspace(0,2*np.pi,100)
def animate(i):
PLOT.set_data(x[i], np.sin(x[i]))
print("test")
return PLOT,
fig = plt.figure()
sub = fig.add_subplot(111, xlim=(x[0], x[-1]), ylim=(-1, 1))
PLOT, = sub.plot([],[])
animation.FuncAnimation(fig, animate, frames=len(x), interval=10, blit=True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.linspace(0,2*np.pi,100)
fig = plt.figure()
sub = fig.add_subplot(111, xlim=(x[0], x[-1]), ylim=(-1, 1))
PLOT, = sub.plot([],[])
def animate(i):
PLOT.set_data(x[:i], np.sin(x[:i]))
# print("test")
return PLOT,
ani = animation.FuncAnimation(fig, animate, frames=len(x), interval=10, blit=True)
plt.show()
You need to keep a reference to the animation object around, otherwise it gets garbage collected and it's timer goes away.
There is an open issue to attach a hard-ref to the animation to the underlying Figure object.
As written, your code well only plot a single point which won't be visible, I changed it a bit to draw up to current index

Categories

Resources