Creating animations

Matplotlib provides two main interfaces for creating animations: TimedAnimation and FuncAnimation. TimedAnimation is useful for creating time-based animations, while FuncAnimation can be used to create animations according to a custom-defined function. Given the much higher level of flexibility offered by FuncAnimation, we will only explore the use of FuncAnimation in this section. Readers can refer to the official documentation (https://matplotlib.org/api/animation_api.html) for more information about TimedAnimation.

FuncAnimation works by repeatedly calling a function that changes the properties of Matplotlib objects in each frame. In the following example, we've simulated the change in median weekly earnings by assuming a 5% annual increase. We are going to create a custom function--animate--which returns Matplotlib Artist objects that are changed in each frame. This function will be supplied to animation.FuncAnimation() together with a few more extra parameters:

import textwrap 
import matplotlib.pyplot as plt
import random
# Matplotlib animation module
from matplotlib import animation
# Used for generating HTML video embed code
from IPython.display import HTML


# Adapted from previous example, codes that are modified are commented
fig, ax = plt.subplots(figsize=(6,7))
ind = range(df.shape[0])
rects = ax.barh(ind, df["Median usual weekly earnings ($)"], height=0.5)
ax.set_xlabel('Median weekly earnings (USD)')
ylabels=[textwrap.fill(label,15) for label in df["Educational attainment"]]
ax.set_yticks(ind)
ax.set_yticklabels(ylabels)
fig.subplots_adjust(left=0.3)

# Change the x-axis range
ax.set_xlim(0,7600)
# Add a text annotation to show the current year
title = ax.text(0.5,1.05, "Median weekly earnings (USD) in 2016",
bbox={'facecolor':'w', 'alpha':0.5, 'pad':5},
transform=ax.transAxes, ha="center")

# Animation related stuff
n=30 #Number of frames

# Function for animating Matplotlib objects
def animate(frame):
# Simulate 5% annual pay rise
data = df["Median usual weekly earnings ($)"] * (1.05 ** frame)

# Update the bar heights
for i, rect in enumerate(rects):
rect.set_width(data[i])

# Update the title
title.set_text("Median weekly earnings (USD) in {}".format(2016+frame))

return rects, title

# Call the animator. Re-draw only the changed parts when blit=True.
# Redraw all elements when blit=False
anim=animation.FuncAnimation(fig, animate, blit=False, frames=n)

# Save the animation in MPEG-4 format
anim.save('test.mp4')

# OR--Embed the video in Jupyter notebook
HTML(anim.to_html5_video())

Here is the screen capture of one of the video frames:

In this example, we output the animation in the form of MPEG-4-encoded videos. The video can also be embedded in Jupyter Notebook in the form of an H.264-encoded video. All you need to do is call the Animation.to_html5_video() method and supply the returned object to IPython.display.HTML. Video encoding and HTML5 code generation will happen automatically behind the scenes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset