import pandas as pd
import numpy as np
from plotnine import ggplot, aes, geom_path, theme, theme_void, lims
from plotnine.animation import PlotnineAnimation
# for animation in the notebook
from matplotlib import rc
"animation", html="html5") rc(
Spiral Animation ###
In [1]:
How to create Animations
The PlotnineAnimation
methods takes a sequence of plots and animates them. The best way to create the sequence is to use a function that generates plots.
NOTE: When creating the plots make sure all the plots have scales with the same limits for each aesthetic, including the x
and y
aesthetics.
In [2]:
# Parameters used to control the spiral
= 100
n = 1.3
tightness = 1
kmin = 25
kmax = 25
num_frames = np.linspace(-np.pi, np.pi, n)
theta
def plot(k):
# For every plot we change the theta
= theta * k
_theta
# Polar Equation of each spiral
= tightness * _theta
r
= pd.DataFrame({
df "theta": _theta,
"r": r,
"x": r * np.sin(_theta),
"y": r * np.cos(_theta)
})
= (
p
ggplot(df)+ geom_path(aes("x", "y", color="theta"), size=1)
+ lims(
# All the plots have scales with the same limits
=(-130, 130),
x=(-130, 130),
y=(-kmax * np.pi, kmax * np.pi),
color
)+ theme_void()
+ theme(
=1,
aspect_ratio# Make room on the right for the legend
={"right": 0.85},
subplots_adjust
)
)return p
# It is better to use a generator instead of a list
= (plot(k) for k in np.linspace(kmin, kmax, num_frames))
plots = PlotnineAnimation(plots, interval=100, repeat_delay=500)
ani # ani.save('/tmp/animation.mp4')
ani
The final image of the spiral
In [3]:
# Gallery Plot
plot(kmax)