Animating Your Python Visualizations: A Quick and Simple Guide
Written on
Chapter 1: Introduction to Animation in Python
In the realm of Data Science and Data Analytics, visual representation is paramount. Sometimes, we wish to enhance our plots with animations for better presentations and insights. However, many libraries, like matplotlib.animation, can be quite complex. If you're looking for a straightforward method to create animated graphs, the ImageIO library offers an easier alternative. This library is excellent for image manipulation and can efficiently combine images to produce GIFs.
Before diving into the code, ensure you have the ImageIO library installed. You can do this using pip:
pip install imageio
Section 1.1: Creating a Basic Line Chart
To illustrate, we can start with a simple line chart. We will create a NumPy array containing 50 random integers and plot them.
import numpy as np
import matplotlib.pyplot as plt
import imageio
np.random.seed(0)
SIZE = 50
y = np.random.randint(-5, 5, SIZE)
plt.plot(y)
plt.ylim(-10, 10)
plt.show()
In this code, the random seed ensures that the results can be consistently reproduced. The SIZE constant allows you to adjust the number of integers generated. The y-values are constrained between -5 and 5, and the y-axis limits are set to provide a clearer view.
Now that we have a static line chart, let's animate it by plotting points incrementally and creating a GIF from the frames.
Section 1.2: Generating Frames for Animation
The first step in animation is to create frames. We will plot the line chart incrementally, saving each iteration as a separate PNG image.
for i in range(2, SIZE + 1):
plt.plot(y[0:i])
plt.ylim(-10, 10)
plt.savefig(f'line-{i}.png')
plt.close()
This loop starts at 2 points since a single point doesn't create a valid line chart and continues until it reaches 50 points. It is crucial to maintain consistent y-axis limits across frames to avoid discrepancies.
After executing this code, you will generate 49 PNG files in your working directory.
Section 1.3: Creating the GIF
Next, we can combine the PNG images into a GIF using ImageIO:
with imageio.get_writer('line.gif', mode='i') as writer:
for i in range(2, SIZE + 1):
image = imageio.imread(f'line-{i}.png')
writer.append_data(image)
Using a with statement simplifies the process, automatically handling the closing of the writer. The output file will be named line.gif, and the mode='i' flag indicates that the input will consist of image files.
If the frames are no longer needed, you can delete them using the following code:
import os
for i in range(2, SIZE + 1):
os.remove(f'line-{i}.png')
Chapter 2: Enhancements and Advanced Examples
The first video, "Animating Plots In Python Using Matplotlib," provides a comprehensive overview of animation techniques in Python.
The second video, "Matplotlib Animations in Python," delves deeper into creating animations with Matplotlib.
Section 2.1: Improving the Animation
While the previous GIF successfully animated the line chart, the x-axis also shifted during the animation. If we want to stabilize the x-axis, we can modify the frame generation code:
for i in range(2, SIZE + 1):
plt.plot(y[0:i])
plt.ylim(-10, 10)
plt.xlim(0, 50)
plt.savefig(f'line-{i}.png')
plt.close()
This adjustment ensures that the x-axis remains fixed throughout the animation.
Section 2.2: A More Complex Example: Bar Charts
Now, let's explore animating a bar chart. We'll need to define x and y values for the bars. Each frame will represent a different y-value.
x_axis = [1, 2, 3]
y_axis_list = [
[0, 0, 0],
[1, 2, 3],
[3, 2, 1],
[5, 5, 5],
[7, 7, 7],
[9, 2, 9],
[2, 9, 2],
[1, 1, 1],
[9, 9, 9],
[0, 0, 0]
]
Now, let’s create the frames for the bar chart GIF.
png_files = []
for i, y_axis in enumerate(y_axis_list):
plt.bar(x_axis, y_axis)
plt.ylim(0, 10)
filename = f'bar-{i}.png'
png_files.append(filename)
plt.savefig(filename)
plt.close()
with imageio.get_writer('bar.gif', mode='i') as writer:
for filename in png_files:
image = imageio.imread(filename)
writer.append_data(image)
This code generates a GIF from the created bar chart frames.
Section 2.3: Smoother Transitions
To enhance the animation, we can introduce additional frames between the major states for smoother transitions.
smooth_coef = 10
png_files = []
for i in range(0, len(y_axis_list) - 1):
y_axis_curr = y_axis_list[i]
y_axis_next = y_axis_list[i + 1]
y_diff = np.array(y_axis_next) - np.array(y_axis_curr)
for j in range(0, smooth_coef + 1):
y_axis = (y_axis_curr + (y_diff / smooth_coef) * j)
filename = f'bar-{i}-{j}.png'
png_files.append(filename)
plt.bar(x_axis, y_axis)
plt.ylim(0, 10)
plt.savefig(filename)
plt.close()
This approach adds transition frames, improving the visual flow of the GIF.
Section 2.4: Utilizing Other Libraries
The method discussed is versatile and not limited to Matplotlib. For example, you can also use Seaborn to create the bar chart:
import seaborn as sns
sns.set_style('darkgrid')
sns.barplot(x=x_axis, y=y_axis)
This flexibility allows you to create animations with various visualization libraries.
Conclusion
In this guide, we explored a method to animate Python visualizations into GIFs without relying on specialized animation libraries. By generating individual frames and combining them using ImageIO, we can create engaging animations. This technique is versatile, allowing for the use of any library capable of producing image files.
While this method might not be the most efficient for large datasets due to the need for multiple individual files, it offers an intuitive way to create animations. If you found this article helpful, consider supporting writers on platforms like Medium!