banner



How To Download Animations From Jupyter Notebook

Creating animation graph with matplotlib FuncAnimation in Jupyter Notebook

Photo past Isaac Smith on Unsplash

Matplotlib is 1 of the most pop plotting libraries for exploratory data analysis. It's the default plotting backend in Pandas and other popular plotting libraries are based on it, for instance, seaborn. Plotting a static graph should piece of work well in almost cases, but when you are running simulations or doing time-series information analysis, basic plots may non always be enough. You may want to show an blitheness that helps you empathize how the state changes over fourth dimension.

In this commodity, you'll acquire how to create animations using matplotlib in Jupyter Notebook. This article is structured every bit follows:

  1. Interactive Plot in Jupyter Notebook
  2. Embedded HTML5 video in Jupyter Notebook

Delight check out the Notebook for source code.

For sit-in, we will be creating a moving sine wave, and below is 1 frame instance:

          import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(ten)
plt.plot(x, y)
plt.show()

Image by Author

1. Interactive Plot in Jupyter Notebook

In order to create an interactive plot in Jupyter Notebook, you first demand to enable interactive plot as follows:

          # Enable interactive plot
%matplotlib notebook

After that, we import the required libraries. Especially FuncAnimation class that can be used to create an animation for you.

          import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

Next, we demand to create an initial state of the animation figure. Nosotros call subplots() without any arguments to create a Figure fig and a single Axes ax. We prepare the x range to (0, 2*Pi) and y range to (-1.ane,1.1) to avert them to exist constantly changing.

                      fig, ax = plt.subplots()                                line, = ax.plot([])     # A tuple unpacking to unpack the only plot          ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1.1, one.i)

We then create a function animate() that's going to be called by the FuncAnimation. The part takes one statement frame_num — the electric current frame number. What we want to exercise here is to change data for our line according to the frame number.

          def breathing(frame_num):
y = np.sin(ten + 2*np.pi * frame_num/100)
line.set_data((x, y))
return line

Finally, we create our animation object by calling FuncAnimation with iv arguments

  • The first argument fig is the reference to the figure we created
  • The second argument animate is the function nosotros created to call at each frame to update the plot.
  • The third argument is frames=100, and it defines the number of frames for "one circular of animation"
  • Finally, the interval=xx argument sets the delay (in milliseconds) between frames. 20 is equivalent to 50FPS (1000ms / 20 = 50 FPS). If the number is besides large you wait a actually long time, if the number is too minor, it would exist faster than your eyes could run across. In general, we demand FPS greater than xvi for smooth blitheness (Human eyes can only receive 10–12 frames [1]).
          anim = FuncAnimation(fig, animate, frames=100, interval=xx)          plt.show()        

Image by Writer

Please cheque out Notebook for the source code

2.Embedded HTML5 video in Jupyter Notebook

In the previous instance, we have created a nice sine wave animation. Even so, the plot is animating only when the code is running. Of course, nosotros could take a screen capture, but that's not efficient when yous want to share your Jupyter Notebook online.

What we tin can exercise is convert the animation into an HTML5 video and embed it in Jupyter Notebook. We volition be using FFmpeg for conversion. If you don't accept it, you first need to follow the instruction to download FFmpeg and unzip it.

Subsequently that, nosotros import the required libraries and fix 'ffmpeg_path' to the path to your local ffmpeg executable:

          import matplotlib.pyplot every bit plt
from matplotlib.animation import FuncAnimation
from IPython import display
plt.rcParams['animation.ffmpeg_path'] = '/path_to_your/ffmpeg'

Creating animation is the aforementioned equally the previous example.

          fig, ax = plt.subplots()          line, = ax.plot([])   # A tuple unpacking to unpack the only plot          ax.set_xlim(0, two*np.pi)
ax.set_ylim(-ane.i, 1.1)
def animate(frame_num):
y = np.sin(x + 2*np.pi * frame_num/100)
line.set_data((ten, y))
return line
anim = FuncAnimation(fig, animate, frames=100, interval=xx)

But instead of plt.show() to plot it, we are calling anim.to_html5_video() method to convert the animation result into an HTML5 video. We then need to get the HTML code that does the embedding for this video and that is done by calling IPython display.HTML(video). Finally, we call display.display(html) to embed the HTML code in Jupyter Notebook.

          video = anim.to_html5_video()
html = brandish.HTML(video)
display.display(html)
plt.close() # avert plotting a spare static plot

Image by Writer

Delight check out Notebook for source code

Conclusion

In this commodity, we have learned 2 approaches to create matplotlib animation in Jupyter Notebook. Creating an animation plot can help you running simulations and doing time-series information assay.

I hope this article volition assist you to save time in learning matplotlib. I recommend you to bank check out the documentation for more options & setting and to know about other things you can do.

Thanks for reading. Please cheque out the notebook for the source lawmaking and stay tuned if you lot are interested in the applied aspect of auto learning.

You lot may be interested in some of my other Data Visualization and Pandas manufactures:

  • Python Interactive Data Visualization with Altair
  • Interactive Information Visualization for exploring Coronavirus Spreads
  • 10 tricks for converting numbers and strings to Datetime in Pandas
  • All Pandas json_normalize() y'all should know for flattening JSON
  • Using Pandas method chaining to better code readability
  • How to exercise a Custom Sort on Pandas DataFrame
  • All the Pandas shift() you lot should know for data analysis

More tutorials can be plant on my Github

Reference

  • https://stopmotionmagazine.com/why-your-frame-charge per unit-fps-matters-in-animation/

Source: https://towardsdatascience.com/matplotlib-animations-in-jupyter-notebook-4422e4f0e389

Posted by: dunnfamenter87.blogspot.com

0 Response to "How To Download Animations From Jupyter Notebook"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel