avatarLeonie Monigatti

Summary

This article provides a tutorial on creating GIFs from Matplotlib plots in Python using the imageio library to effectively visualize 2-dimensional time series data.

Abstract

The article explains how to create animated GIFs from Matplotlib plots in Python, which is particularly useful for visualizing the relationship between two features over time in 2-dimensional time series data. It outlines a three-step process: creating a function to plot time-dependent frames, plotting all frames of the GIF, and combining these frames into a GIF using imageio. The author emphasizes that GIFs can more clearly represent the dynamic relationship between variables compared to static line plots, which may not effectively convey the temporal aspect of the data. The tutorial includes code snippets and example visualizations to guide the reader through the process of generating a GIF with Matplotlib and imageio, and it concludes with the benefits of using GIFs for data visualization.

Opinions

  • The author suggests that GIFs are a superior method for visualizing 2-dimensional time series data compared to traditional line plots.
  • It is recommended to set the parameters transparent = False and facecolor = 'white' when creating frames for the GIF to avoid strange-looking effects.
  • The author expresses a preference for GIFs as a data visualization tool because they can show the evolution of a relationship over time, which is not possible with static plots.
  • The article implies that visualizing data with GIFs can lead to more insightful analysis, especially when dealing with data that has a temporal component, such as longitude and latitude or x and y coordinates.
  • The author provides an option to make the GIF stop after one loop, indicating a consideration for user experience when viewing the animation.

How to Create a GIF from Matplotlib Plots in Python

A data visualization technique for 2-dimensional time series data using imageio

GIF created with Matplotlib and imageio (Image by the author)

We all know that line plots are the most intuitive way to visualize a time series. But how would you visualize a time series with two features that have a relationship, like x and y coordinates or longitude and latitude? GIFs are a great way to visualize 2-dimensional time series data.

GIFs are a great way to visualize 2-dimensional time series data.

Let’s have a look at the following example.

x = [1, 2, 3, 4, 4, 4, 4, 3, 2, 1, 1, 1, 1]
y = [1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 3, 2, 1]
time = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

You can first plot each feature over the time with a line plot. But with this data visualization, the relationship between the two features is unclear.

Line plots of two separate time series (Image by the author)

Next, you can plot x over y, which reveals the relationship between the two features. But now you are missing the time aspect.

x over y (Image by the author)

To visualize the relationship between the two features and the time, we can use a GIF.

This tutorial will show you how to quickly create a GIF in Python with three simple steps.

How to Create a GIF in Python

You can create a GIF in Python in just three simple steps using the libraries Matplotlib and imageio:

  1. Create a Function to Plot Time-Dependent Frames with Matplotlib
  2. Plot All the Frames of the GIF
  3. Combine the Frames Into a GIF with imageio

For this tutorial, we will use Matplotlib to plot the single frames of the GIF and imageio to combine the single frames into one GIF.

import matplotlib.pyplot as plt
import imageio

1. Create a Function to Plot Time-Dependent Frames

First, you will create a function create_frame(t) that plots a single frame of the GIF at one specific timestamp and saves it with a unique name.

I recommend setting the parameters transparent = False and facecolor = 'white' to avoid getting strange-looking effects in your GIFs due to overlapping single transparent frames.

def create_frame(t):
    fig = plt.figure(figsize=(6, 6))
    plt.plot(x[:(t+1)], y[:(t+1)], color = 'grey' )
    plt.plot(x[t], y[t], color = 'black', marker = 'o' )
    plt.xlim([0,5])
    plt.xlabel('x', fontsize = 14)
    plt.ylim([0,5])
    plt.ylabel('y', fontsize = 14)
    plt.title(f'Relationship between x and y at step {t}',
              fontsize=14)
    plt.savefig(f'./img/img_{t}.png', 
                transparent = False,  
                facecolor = 'white'
               )
    plt.close()

2. Plot All the Frames of the GIF

Next, all you have to do is to plot all the frames of the GIF.

for t in time:
    create_frame(t)
All single frames of the GIF plotted with Matplotlib (Image by the author)

And save all of the single frames into an array called frames.

frames = []
for t in time:
    image = imageio.v2.imread(f'./img/img_{t}.png')
    frames.append(image)

3. Combine the Frames Into a GIF

Finally, all you have to do is save the frames to a GIF with the mimsave method. You can adjust the GIF’s frames per second (fps) with the fps parameter.

imageio.mimsave('./example.gif', # output gif
                frames,          # array of input frames
                fps = 5)         # optional: frames per second

The resulting GIF is shown below.

GIF created with Matplotlib and imageio (Image by the author)

If you want the GIF to stop after the last frame, add the parameter loop = 1 to the mimsave method.

imageio.mimsave('./example.gif', 
                frames, 
                fps = 5, 
                loop = 1)
GIF created with Matplotlib and imageio that stops after one loop at the last frame (Image by the author)

Conclusion

Visualizing 2-dimensional time series data with line plots can be ineffective because it does not show the relationship between the two features. Using GIFs is a better data visualization alternative for 2-dimension time series data like longitude and latitude or x and y coordinates.

In this brief tutorial, you learned how you can create a GIF with Matplotlib and imageio in Python in just three simple steps:

  1. Create a Function to Plot Time-Dependent Frames with Matplotlib
  2. Plot All the Frames of the GIF
  3. Combine the Frames Into a GIF with imageio

Enjoyed This Story?

Here is a collection of my other Time Series Analysis and Forecasting articles:

Subscribe for free to get notified when I publish a new story.

Find me on LinkedIn, Twitter, and Kaggle!

Data Visualization
Python
Time Series Analysis
Data Science
Editors Pick
Recommended from ReadMedium