\(\:\)

Animations In Python


There is a common saying: "A picture is worth a thousand words!" But what about animations created out of pictures? An easy and fast understandable way to make an animation is the flip book method that one should be familiar with since play school times. The best Python library using this principle is imageio. What makes imageio especially neat is the fact that after you know how to create the single plots of your animation, further needed is only a simple for loop to generate the gif. Other libraries like matplotlib with matplotlib.animation are similar to use but not as straight forward and simple for beginners like imageio. An example code on how to create an gif with imageio is given below, just click the button or go directly to github. The example curve we investigated is the most important curve in \(\mathbb{R}^2\) and given by: $$c(t)=\begin{pmatrix} t \\ |t| \pm \sqrt{1-t^2} \end{pmatrix},\:\:\:\:\:\:\:\:\:\:\:\:t\in[-1,1]$$ \(c(t)\) is a constant reminder that no matter what we do we should always make sure that we do these things with love. After all, it is the passioned flame living in peoples heart that drives them and there is no greater tragedy than letting this flame expire.

Figure 1: shows the curve \(c(t)\) mentioned in the text. The gif was created from the Python library imageio, which uses a flip book method. It is the most important curve in \(\mathbb{R}^2\). Make sure to remember its shape.

""" 
The code below was written by @author: https://github.com/DianaNtz and is an 
example on how to create an animated gif with the library imageio. For details 
on requirements and licences see https://github.com/DianaNtz/Animated-Heart-Curve.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import imageio
n=100 #gifs worth in units of 10**3 words :)
t=np.linspace(-1,1,n-1)
filenames = []
for i in range(0,n):
    #plot the curve
    fig, ax = plt.subplots(figsize=(7,7))
    ax.plot(t[:i],np.sqrt((t[:i])**2)+np.sqrt(1-(t[:i])**2),"-",
linewidth=3.0,color='deeppink',label='$(\:t,|t|+\sqrt{1-t^2}\:)$')
    ax.plot(-t[:i],np.sqrt((t[:i])**2)-np.sqrt(1-(t[:i])**2), "-m",
linewidth=3.0,label='$(\:t,|t|-\sqrt{1-t^2}\:)$')
    ax.set_xlim(-1.5,1.5)
    ax.set_ylim(-1.5,2.5)
    plt.xticks(fontsize= 16) 
    plt.yticks(fontsize= 16)
    plt.legend(loc=1,fontsize= 16)    
    #create file name for index i 
    filename ='bla{0:.0f}.png'.format(i)
    #append file name to the list filename
    filenames.append(filename)    
    #save the plot
    plt.savefig(filename,dpi=100)
    plt.close()    
#build the gif
with imageio.get_writer('Herz.gif', mode='I') as writer:
    for filename in filenames:
        image = imageio.imread(filename)
        writer.append_data(image)       
#remove saved figures 
for filename in set(filenames):
    os.remove(filename)

\(\:\)