![]() |
|
[Tut] Matplotlib Animation – A Helpful Illustrated Guide - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Matplotlib Animation – A Helpful Illustrated Guide (/thread-95038.html) |
[Tut] Matplotlib Animation – A Helpful Illustrated Guide - xSicKxBot - 05-13-2020 Matplotlib Animation – A Helpful Illustrated Guide Creating animations in matplotlib is reasonably straightforward. However, it can be tricky when starting, and there is no consensus for the best way to create them. In this article, I show you a few methods you can use to make amazing animations in matplotlib. Matplotlib Animation Example The hardest thing about creating animations in matplotlib is coming up with the idea for them. This article covers the basic ideas for line plots, and I may cover other plots such as scatter and 3D plots in the future. Once you understand these overarching principles, you can animate other plots effortlessly. There are two classes you can use to create animations: Code: FuncAnimationCode: ArtistAnimation.Code: FuncAnimationTo use Code: FuncAnimation,Code: animateTo create an animation with Code: FuncAnimation
Let’s create a sin wave that matplotlib ‘draws’ for us. Note that this code may look strange to you when you first read it. Creating animations with matplotlib is different from creating static plots. Code: # Standard imports
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimationImport NumPyand matplotlib using their standard aliases and Code: FuncAnimationCode: matplotlib.animationCode: # Set up empty Figure, Axes and Line objects
fig, ax = plt.subplots()
# Set axes limits so that the whole image is included
ax.set(xlim=(-0.1, 2*np.pi+0.1), ylim=(-1.1, 1.1))
# Draw a blank line
line, = ax.plot([], [])![]() Set up the Code: FigureCode: AxesCode: plt.subplots()Code: ax.set()Then, I did something you have probably never done before: I drew a blank line. You need to do this because Code: animateNote that you must include a comma after Code: line,Code: lineCode: # Define data - one sine wave
x = np.linspace(0, 2*np.pi, num=50)
y = np.sin(x)Next, define the data you want to plot. Here, I am plotting one sine wave, so I used Code: np.linspace()Code: yCode: np.sin()Code: xCode: # Define animate function
def animate(i): line.set_data(x[:i], y[:i]) return line,Define the Code: animate(i)Code: iCode: line.set_data()Code: iCode: xCode: yCode: line,Code: # Pass to FuncAnimation
anim = FuncAnimation(fig, animate, frames=len(x)+1, interval=30, blit=True)Create a Code: FuncAnimationCode: FigureCode: animateNext, set the number of Code: framesCode: len(x)+1Code: xCode: range()Code: xThe Code: intervalFinally, set Code: blit=TrueCode: # Save in the current working directory
anim.save('sin.mp4')I saved the animation as a video called ‘sin.mp4’ to the current working directory. https://blog.finxter.com/wp-content/uploads/2020/05/sin-2.mp4 Open your current working directory, find the saved video, and play it. Congratulations! You’ve just made your first animation in matplotlib! Some of the steps you take to create animations are unique and may feel unusual the first time you try them. I know I felt strange the first time I used them. Don’t worry, the more you practice and experiment, the easier it becomes. Here’s the full code: Code: # Standard imports
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation # Set up empty Figure, Axes and Line objects
fig, ax = plt.subplots()
# Set axes limits so that the whole image is included
ax.set(xlim=(-0.1, 2*np.pi+0.1), ylim=(-1.1, 1.1))
# Draw a blank line
line, = ax.plot([], []) # Define data - one sine wave
x = np.linspace(0, 2*np.pi, num=50)
y = np.sin(x) # Define animate function
def animate(i): line.set_data(x[:i], y[:i]) return line, # Pass to FuncAnimation
anim = FuncAnimation(fig, animate, frames=len(x)+1, interval=30, blit=True) # Save in the current working directory
anim.save('sin.mp4')Note that if this final step did not work for you, it’s probably because you don’t have the right libraries installed – I’ll show you what to install right now. Related:
Matplotlib Animation Save To save your animation in matplotlib, use the Code: .save()Code: FuncAnimationMatplotlib Animation Save Mp4 To save animations as mp4 videos, first, install the FFmpeg library. It’s an incredibly powerful command-line tool, and you can download it from their official site, Github, or, if you use anaconda, by running Code: conda install ffmpegOnce you have created your animation, run Code: anim.save('name.mp4', writer='ffmpeg')Note that the default writer is FFmpeg, and so you don’t have to explicitly state it if you don’t want to. Matplotlib Animation Save Gif To save animations as gifs, first, install the ImageMagick library. It is a command-line tool, and you can download it from their official site, GitHub, or if you use anaconda, by running Code: conda install -c conda-forge imagemagickOnce you have created your animation, run Code: anim.save('name.gif', writer='imagemagick')Code: anim.save('sin.gif', writer='imagemagick')![]() Note that both ImageMagick and FFmpeg are command-line tools and not python libraries. As such, you cannot install them using Code: pipMatplotlib Animation Jupyter If you write your code in Jupyter notebooks (something I highly recommend), and don’t want to save your animations to disk every time, you may be disappointed to hear that your animations do not work out of the box. By default, Jupyter renders plots as static png images that cannot be animated. To fix this, you have a couple of options to choose from:
If you run Code: %matplotlib notebookCode: # Run at the top of your notebook
%matplotlib notebookAs I cannot show you interactive Jupyter windows in a blog post, the above video shows you the result of running the sin drawing curve above. This method is by far the simplest but gives you the least control. For one thing, the buttons at the bottom do nothing. Plus, it keeps running until you click the off button at the top… but when you do, you have no way to turn it on again! I much prefer using the default Code: %matplotlin inlineThe other option is to change the Code: plt.rcParamsIf you print it to the screen, you can see all the parameters it controls. The one you are interested in is Code: animation.htmlCode: noneCode: 'html5'Code: 'jshtml'Let’s see what happens when you set Code: plt.rcParamsCode: 'html5'Code: plt.rcParams['animation.html'] = 'html5'
animNow the animation is rendered as an HTML5 video that plays as a loop. You can start/stop it using the play/pause buttons, but that’s about it. In my experience, this video plays much smoother than the interactive windows produced by Code: %matplotlib notebookNow let’s look at the much more powerful option: Code: 'jshtml'Code: plt.rcParams['animation.html'] = 'jshtml'
animNow your animations are displayed in interactive javascript windows! This option is by far the most powerful one available to you. Here are what each of the keys do (starting from the far left):
Moreover, you can choose to play it ‘Once’, ‘Loop’ infinitely or play forwards and backward indefinitely using ‘Reflect’. To have all your animations render as either HTML5 video or in interactive javascript widgets, set Code: plt.rcParamsConclusion Excellent! You now know how to create basic animations in matplotlib. You know how to use Code: FuncAnimatonYou’ve seen how to create ‘drawing’ plots, but there are many other things you can do, such as creating moving plots, animating 3D plots, and even scatter graphs. But we’ll leave them for another article. Where To Go From Here? Do you wish you could be a programmer full-time but don’t know how to start? Check out the pure value-packed webinar where Chris – creator of Finxter.com – teaches you to become a Python freelancer in 60 days or your money back! https://tinyurl.com/become-a-python-freelancer It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar. These are proven, no-BS methods that get you results fast. This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed. https://tinyurl.com/become-a-python-freelancer |