Skip to content
Snippets Groups Projects
Commit 418b3c35 authored by Chrysanthos KINDYNIS's avatar Chrysanthos KINDYNIS
Browse files

A guide on making animated figures with Matplotlib

parent f0e4cd99
No related branches found
No related tags found
1 merge request!7Fig animation
# Creating Animated Figures with Matplotlib
In this chapter, we will explore creating animated figures using Matplotlib animations.
## Requirements
Before getting started with creating animated figures using Matplotlib, make sure you have the following requirements in place:
- Python installed on your system
- Matplotlib library installed
- IPython library installed
## Sources
To learn more about creating animated figures using Matplotlib, you can refer to the following resources:
- [Matplotlib Animation API](https://matplotlib.org/stable/api/animation_api.html): This documentation provides insights into how the animation method works internally and offers multiple coding examples.
- [Matplotlib FuncAnimation](https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html): Here, you can find detailed information about the parameters of the FuncAnimation function and the methods it provides.
In the next sections, we will guide you through the main steps, provide a brief explanation, and present a code example.
## The method
The `FuncAnimation` module creates an animation by repeatedly calling a function (`func` argument). Each call generates one frame of the animation. The `frames` argument specifies the source of data to pass to the `func` for each frame.
The main arguments needed for the animation are as follows:
- `fig`: A figure object that serves as the canvas for the animation.
- `func`: The function to call at each frame. This function should update the information of the figure object to capture the frame in the animation.
- `frames=None`: The domain of values for which a frame will be created. The `func` function is called with each value from the `frames` argument.
It's important to note that the `funcAnimation` first calls the `func` function and then draws the content of the `fig` object at each frame. Therefore, the `func` function should update the figure object to reflect the desired changes for each frame.
> **Note:** For more information and examples, refer to the [Matplotlib Animation API documentation](https://matplotlib.org/stable/api/animation_api.html).
## Coding example
The following code example demonstrates how to create an animated figure using Matplotlib:
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
plt.rcParams["animation.html"] = "jshtml" # Set the animation format to "jshtml"
x = np.linspace(0, 2 * np.pi, 100)
fig, ax = plt.subplots() # Create a figure and axes object
line, = ax.plot(x, np.sin(x))
def update(frame):
line.set_ydata(np.sin(x + frame)) # Update the y-data of the line with the new frame value
ani = animation.FuncAnimation(fig, update, frames=x) # Create the animation object
plt.close(fig) # Prevent the initial figure from being displayed inline
HTML(ani.to_jshtml()) # Display the animation as HTML
```
Or another example, which can be found in the [Open Quantum Sensing and Measurement Notes](https://interactivetextbooks.tudelft.nl/qsm/src/5_wigner_2.html) is:
```python
from qutip import *
N = 30
fig, ax = plt.subplots(1, 1, figsize=(4, 4))
def update(phi):
ax.cla()
psi = coherent(N,3*np.exp(1j*phi)) + coherent(N,-3*np.exp(1j*phi))
plot_wigner(psi,fig=fig,ax=ax)
phi_values = np.linspace(0, 2*np.pi, 100)
anim = animation.FuncAnimation(fig, update, frames=phi_values)
plt.close(fig) # Close the figure to prevent it from displaying inline
HTML(anim.to_jshtml())
```
## General process
The general process to create an animated figure using Matplotlib is as follows:
1. Ensure that the necessary packages are installed.
2. Define the figure object, e.g. using `plt.subplots()`.
3. Specify the frames argument, which determines the domain of values for creating each frame.
4. Define the func function that will be called for each frame. This function should update the figure object accordingly. The first argument will be the frame value and [additional arguments](https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html#:~:text=The%20function%20to%20call%20at%20each%20frame.%20The%20first%20argument%20will%20be%20the%20next%20value%20in%20frames.%20Any%20additional%20positional%20arguments%20can%20be%20supplied%20using%20functools.partial%20or%20via%20the%20fargs%20parameter.) can be added if needed.
5. Create the `FuncAnimation` object by providing the above-mentioned arguments and any other relevant arguments.
6. Set the `animation.html` ([link](https://matplotlib.org/stable/users/explain/customizing.html#:~:text=%2D%20%27jshtml%27%20creates%20a%20JavaScript%20animation)) parameter to "jshtml" to plot the animation as HTML.
7. Generate the HTML representation of the animation using the `.to_jshtml()` function and convert the result to HTML using the `IPython.display.HTML` method.
For more details and examples, refer to the [Matplotlib Animation API documentation](https://matplotlib.org/stable/api/animation_api.html).
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment