top of page

Python - Graph animations

The purpose of this contribution is to test animated graphs in Python and Google Colaboratory. Presentation of animated data is useful part of story telling and looks on the webpage very good. We can use animated graphs to present time trends, movement in an array or any other graph evolution such as thermal reaction. At the end we can present our animation in Html or in rc (runtime configuration, default) format and save it e.g. to gif file by pillowwriter tool.


1. Present the time trend — Sinus, cosinus and their phase


Install and import the needed libraries.


%matplotlib inline

import numpy as np

import matplotlib.pyplot as plt

import seaborn as sns


Create frames for graphs and fill them by data.


# create a figure and axes

fig = plt.figure(figsize=(12,5))

ax1 = plt.subplot(1,2,1)

ax2 = plt.subplot(1,2,2)


# set up the subplots as needed

ax1.set_xlim(( 0, 2))

ax1.set_ylim((-2, 2))

ax1.set_xlabel('Time')

ax1.set_ylabel('Magnitude')

ax2.set_xlim((-2,2))

ax2.set_ylim((-2,2))

ax2.set_xlabel('X')

ax2.set_ylabel('Y')

ax2.set_title('Phase Plane')


# Create objects that will change in the animation.

# Initially empty, have new values in the animation.

# matplotib basic colors for point: k for black, w for white

# matplotib css colors for lines: silver, tan, grey

txt_title = ax1.set_title('')

line1, = ax1.plot([], [], 'silver', lw=2)


# ax.plot returns a list of 2D line objects

line2, = ax1.plot([], [], 'tan', lw=2)

pt1, = ax2.plot([], [], 'k.', ms=20)

line3, = ax2.plot([], [], 'grey', lw=2)

ax1.legend(['sin','cos']);


Define the animation function and fill sequentionaly.


def drawframe(n):

x = np.linspace(0, 2, 1000)

y1 = np.sin(2 * np.pi * (x - 0.01 * n))

y2 = np.cos(2 * np.pi * (x - 0.01 * n))

line1.set_data(x, y1)

line2.set_data(x, y2)

line3.set_data(y1[0:50],y2[0:50])

pt1.set_data(y1[0],y2[0])

txt_title.set_text('Frame = {0:4d}'.format(n))

return (line1,line2)


Create animation object.


from matplotlib import animation

# blit=True updates only the changed parts

anim = animation.FuncAnimation(fig, drawframe, frames=100, interval=20, blit=True )


Render and display animation by HTML or by rc.


# 1. render and display the desired animation by HTML

from IPython.display import HTML

HTML(anim.to_html5_video())


# 2. render and display the desired animation by rc

from matplotlib import rc

# equivalent to rcParams['animation.html'] = 'html5'

rc('animation', html='html5')

anim


Save animation to gif. Fps parameter will set up gif speed.

from matplotlib.animation import FuncAnimation, PillowWriter


# save animation at 20 frames per second

anim.save("sincos.gif", dpi=250, writer=PillowWriter(fps=20))




2. Animated lines


Create 3 lines in an array and save to gif.


# create 3 lines

x1 = np.arange(2, -3, -0.04)

y1 = np.arange(2, -3, -0.04)

x2 = np.arange(3.9, -2, -0.04)

y2 = np.arange(0, 1, 0.01)

x3 = np.arange(0, 1.8, 0.018)

y3 = np.array(x3**2)

fig,ax = plt.subplots()

def animate(i):

ax.clear()

ax.set_xlim(-4,4)

ax.set_ylim(-4,4)

ax.set_title('3 Lines')

line, = ax.plot(x1[0:i], y1[0:i], color = 'black', lw=1)

line2, = ax.plot(x2[0:i], y2[0:i], color = 'tan', lw=1)

line3, = ax.plot(x3[0:i], y3[0:i], color = 'grey', lw=1)

point1, = ax.plot(x1[i], y1[i], marker='.', color='black')

point2, = ax.plot(x2[i], y2[i], marker='.', color='tan')

point3, = ax.plot(x3[i], y3[i], marker='.', color='grey')

return line, line2, line3, point1, point2, point3,

ani = FuncAnimation(fig, animate, interval=40, blit=True, repeat=True, frames=100)

ani.save("lines.gif", dpi=300, writer=PillowWriter(fps=25))

Use HTML to render.

HTML(ani.to_html5_video())



4. Thermal reaction


Use other syntaxes to display more interesting reactions.




5. References


https://scipython.com/blog/a-simple-two-dimensional-brownian-motion-animation/

https://towardsdatascience.com/animated-visualization-of-brownian-motion-in-python-3518ecf28533

https://stackoverflow.com/questions/68960005/saving-an-animated-matplotlib-graph-as-a-gif-file-results-in-a-different-looking

https://jckantor.github.io/CBE30338/toc.html

https://jckantor.github.io/CBE30338/A.03-Animation-in-Jupyter-Notebooks.html

https://jckantor.github.io/CBE30338/A.02-Modular-Approach-to-Simulation-using-Python-Generators.html

https://stackoverflow.com/questions/25333732/matplotlib-animation-not-working-in-ipython-notebook-blank-plot

https://codeburst.io/storytelling-using-animation-in-plotly-1f50a856ba5

https://towardsdatascience.com/animated-bar-plot-in-python-for-time-series-data-8809dbdf9bc

https://veeraldoesdata.com/animated-how-to

https://www.askpython.com/python/examples/animating-data-in-python

https://stackoverflow.com/questions/62335385/animating-a-line-plot-over-time-in-python

https://scipython.com/book2/chapter-7-matplotlib/examples/animating-a-bouncing-ball/

https://matplotlib.org/stable/api/animation_api.html

https://stackoverflow.com/questions/49841865/how-to-animate-multiple-balls-python

https://scipython.com/book2/chapter-7-matplotlib/examples/

https://scipython.com/book2/

https://plotly.com/python/v3/filled-area-animation/


6 views0 comments

Recent Posts

See All

Python - Cryptographic algorithms

In order to examine the basic cryptographic mechanisms, I created the short python codes to generate the old encryption keys for basic...

Python - sktime

There are various libraries created for Python Time Series. Each of them has its own style, contributors and functions. Each library has...

Python - Basic regression comparison

Regression models are the principles of machine learning models as well. They help to understand the dataset distributions. The objective...

Comments


bottom of page