One of the powerful aspects of using Python as a Product Manager is that you have a lot of control over the presentation of your data analysis. And, once you’ve created your amazing plot, you can quickly and easily update the underlying data to provide updates. One of the lesser known aspects of plotting is the ability to create an animation, showing how particular trend changes over time or to incrementally build a complex plot. In this post, we’ll look at a simple method for creating an animated plot from a Pandas DataFrame using the Celluloid module.
Celluloid is a module which wraps some underlying matplotlib functions to create an easy to use animation library for a plot.
Installing it is easy:
pip install celluloid
Now, we should all be ready to go!
Animating a plot
This example builds on the monte carlo business case forecast we worked on in the last post. In this example, we have a dataframe which has columns for one hundred simulations of a business case. We can use celluloid to visualise these being run one at a time, finally adding some percentile outcomes for clarity.
So, in the code below we will loop through each column (stored in the array
forecast_licences_cols), and plot an increasing number of the simulated runs:
from matplotlib import pyplot as plt from celluloid import Camera fig= plt.figure() ax = plt.gca() camera = Camera(fig) for i in range(1,99): mc.df[mc.forecast_licences_cols[:i]].plot(legend=False, color='#444444',linewidth=0.25, alpha=0.33, ax=ax) camera.snap() mc.df[mc.forecast_licences_cols[:100]].plot(legend=False, color='#444444',linewidth=0.25, alpha=0.33, ax=ax) mc.df['forecast_licences_0.5_quantile'].plot(ax=ax, linewidth=2) mc.df['forecast_licences_0.9_quantile'].plot(ax=ax, linewidth=2) mc.df['forecast_licences_0.1_quantile'].plot(ax=ax, linewidth=2) camera.snap() animation = camera.animate() animation.save('montecarlo.mp4')
Each time we call
camera.snap() a frame is taken for our final movie. We save the movie at the end once we’ve iterated through each column.
Viewing celluloid animations in a Jupyter Notebook
If you’re running the code in a Jupyter Notebook then there is a special helper method which will allow for inline viewing of your amazing animation. It makes use of iPythons HTML display capabilities, so, you’ll need to
from IPython.display import HTML
Then, at the end of your animation (after saving the file) simply add the following:
And then you’ll see your video inline!