Animate your Python Graphs with Pillow

Animate your Python plots with the Python library Pillow to bring life to your insights.

Animate your Python Graphs with Pillow

Animate your Python plots with the Python library Pillow to bring life to your insights.

As a data scientist, your ultimate goal is to present your findings in an engaging and informative way.

But how can you ensure that your data is not only visually appealing but also easy to understand?

Scenario

You are a data scientist who has developed an algorithm or performed advanced analysis linked to a dynamic process.

Because you want to show the impact of your solution, you plot the results using a conventional Python library.

A line chart visualizing a pathfinding solution for warehouse Picking using python with connected nodes represented by blue dots. Each node is labeled with a number indicating its sequence in the route. The dashed lines represent the connections between these nodes. This graph is part of a process to optimize a dynamic system by showing the route taken in the solution.
Example of a Pathfinding Solution Graph with Python— (Image by Author)

However, your graphs are not self-explicit and do not reflect the dynamic aspect of the process.

This article will use this example of pathfinding algorithms to show how you can bring additional insights by building GIF animations with Python Pillow.

I. Share Insights with Animated Graphs
1. Problem Statement
Example of pathfinding algorith for warehouse picking
2. Objective
The final result will be an animated GIF of a scatter plot.
II. Generating the Frames with Matplotlib
1. Process
An explaination of the complete workflow to generate an animated plot.
2. Intermediate Plots
We start by generating and saving partial plots
III. Creating Animated GIFs with Python Pillow
1. Step 1: Create the function to convert to a picture
Each intermediate plot will be converted to a picture.
2. Step 2: Build the loop to plot each step
Each step leading to the generation of the final plot
3. Step 3: Create the GIF
Combine the frames in animation by fixing the time per frame using PIL
IV. Conclusion
1. Examples of Animation for Transportation Optimization
This method used to generate an animated map showing delivery routes
2. Automate Graphic Design with PIL
Pillow used to generate warehouse labels with a very efficient workflow

Share Insights with Animated Graphs

Problem Statement

In a Warehouse, walking time from one location to another during the picking route can account for 60% to 70% of the operator’s working time.

Reducing this walking time is the most effective way to increase productivity.

Animated warehouse layout depicted with multiple rows of shelves labeled from A01 to A19. The diagram shows three different animated paths for a picker with routes marked by dashed lines in different colors (blue, black, red). The starting point is labeled “START,” and the paths lead to specific shelves with different colors marking the picked locations.
Example of routes with three locations — (Image by Author)

Therefore, you have developed several algorithms that optimize the route of warehouse operators to reduce their walking distance.

Task

Using an example of a long-picking mission, you want to use a graph to show the difference between the two algorithms.

A graph comparing two solutions from a pathfinding algorithm for warehouse picking route designed with Python. Each node is represented by orange and yellow dots, with numbers inside them to indicate the order of the sequence. Dashed lines connect the nodes in both solutions, allowing a visual comparison between the two algorithms and how they traverse through the picking locations.
Graph with the two solutions — (Image by Author)

Each dot is a picking location, and the numbers represent the order in the operator's picking route.

However, these graphs could be more self-explicit, and we missed the steps that led to this final result.

Objective

Let us animate this graph to see the sequence location by location and understand the difference between the two solutions.

Two animated scatter plots with colored dots, representing two solutions. The upper chart shows orange-colored points connected by dashed lines, and the lower chart shows yellow-colored points connected by dashed lines. Each point is numbered, showing the sequence of steps in each solution, comparing two different pathfinding algorithms’ results.
Example of Outputs — (Image by Author)

The final result would be like this animated gif above, where you can follow the sequence of locations visited for two different algorithms.

Let’s start by generating the frames.

🏫 Discover 70+ case studies using Python to automate reporting, generate interactive visuals and support business optimization 🏪 in this Cheat Sheet


Generating the Frames with Matplotlib

Process

Let me first explain how to plot the graph presented above,

  1. You import a batch of order lines with Order Number, Item Code, Location Coordinates
  2. You run the two algorithms that will create the routes for each order
  3. You export the results with the succession of locations to cover each route
A visual flow diagram illustrating two algorithms (Algorithm 1 and Algorithm 2) processing order data (with details like quantity, item, and picking location). The results from each algorithm provide different picking paths and distances, with Algorithm 1 generating Path 2 and Distance 2, and Algorithm 2 generating Path 1 and Distance 1. This shows a comparison between the two algorithms used for optimizing warehouse picking routes.
Picking Route Optimization Algorithms — (Image by Author)

The results look like this,

  • In Path OR and Path Init you have the succession of 2D coordinates
  • In Distance OR and Distance Init you have the total distance

I won’t detail much about the algorithm.

If you are interested, you can deep dive into the article linked below 👇

Improve Warehouse Productivity using Pathfinding Algorithm with Python | by Samir Saci
Implement Pathfinding Algorithm based on Travelling Salesman Problem Designed with Google AI Operation Research Libraries
Let’s generate the intermediate plots now.

Plot

Let’s take the line with the biggest gap in distance between the two methods and plot the results.

Import the libraries

Because we are going to use scatter plots, we need to extract the coordinates by location for the two solutions.

  • We create two lists of the location coordinates for the two solutions
  • For each list, we create two sublists to take the x-axis and y-axis coordinates

We can use now the lists (x1, y1, x2, y2) to plot the two paths,

  • Plot a dot for each location coordinate (xi, yi) with xi in x1 and yi in y1
  • Link the dots with dotted lines ‘ — ‘
  • Annotate each dot with the order of the location in the path

The final result is a plot of the complete paths,

A graph comparing two solutions from a pathfinding algorithm for warehouse picking route designed with Python. Each node is represented by orange and yellow dots, with numbers inside them to indicate the order of the sequence. Dashed lines connect the nodes in both solutions, allowing a visual comparison between the two algorithms and how they traverse through the picking locations.
Graph with the two solutions — (Image by Author)
How did we arrive at this final result?

Let us detail each step.

Intermediate Plot

You can show the partial path if you truncate the lists used to plot the dotted lines.

A plot of the first three picking locations from two algorithms used for optimizing warehouse routes. Each dot represents a picking location, and the partial paths of the two algorithms are shown. The progression of these paths will eventually lead to a full sequence of locations. The visualization serves as a step in generating an animated sequence comparing the two algorithms’ efficiency in warehouse route optimization.
Three first locations — (Image by Author)

You will reconstitute the picking route by showing partial paths for the first n locations with n varying between 1 and 20.

[Plot 1, Plot 2, … Plot n]: with n the number of locations covered in the path plotted

The final result will be a GIF of these partial paths showing the succession of locations for the two solutions.

Creating Animated GIFs with Python Pillow

The process will be simple,

  1. Generate plots of the partial paths: step-by-step
  2. Convert each plot to a picture using the library io and store it in a list
  3. Create a gif using PIL with the generated list
Step 1: Create the function to convert to a picture

This function will take the figures generated with matplotlib and return a picture with the right format for PIL.

Step 2: Build the loop to plot each step

The images are stored in the list: list_gif

Step 3: Create the GIF

You can create the gif with one line of code,

  • You append the first image with the rest of the list
  • You can select the duration per picture in (ms)
  • Select infinite loop with the option: loop = 0

Final Result

Final Resuls of Animated Scatter Plot using Python GIF
Final Results — (Image by Author)

You can now see the succession of picking locations and understand where the two algorithms differ.

Conclusion

With this straightforward example, you can understand the different steps to follow to generate your animated graphs,

  1. Build a loop that will generate all the frames of your gif
  2. Create a function to convert your plots to image
  3. Build a GIF with all the frames, choosing the speed and the number of loops.

Examples of Animation for Transportation Optimization

You can find other applications of this method for more operational case studies in my previous articles.

Animated detailed map of eastern China, showing major cities like Nanjing, Hangzhou, and Suzhou. The map includes 14 routes marked with colored lines connecting different cities, representing transportation routes for deliveries on 2016–09–01. Black, red, and blue lines connect cities along key logistics corridors, providing insights into delivery patterns for road transportation optimization with Python.
Transportation Route — (Image by Author)

In the animation above, multiple routes are visualized to deliver hypermarkets from a distribution centre in Shanghai.

A simplified illustration of a truck route delivering to six retail stores. The truck starts at the distribution center, travels between stores, and the visual includes a table showing store names, truck ID, and volume (m3). The truck’s path is depicted with dotted lines, providing a clear overview of route efficiency and store delivery patterns.
Distribution Operations for Retail — (Image by Author)

The idea is to monitor trucks' routing to ensure they deliver the maximum number of stores per trip.

What’s the objective? Reduce costs and CO2 emissions.
A bar chart displaying monthly cost (in RMB/ton) and average truck size (in tons). Bars represent cost data while a red line shows fluctuations in truck size. This comparison highlights trends in cost and truck utilization, with noticeable peaks and dips, aiding in cost optimization efforts for transportation.
Costs Analysis per Month — (Image by Author)

With this animated plot, we can visualize the routes designed by planners, understand the patterns and find optimization levers.

For more information, check the link below 👇

Road Transportation Network Visualization
Build Visualizations of your FTL Network Performance: deliveries/route, cost per ton and trucks size
Do you need support to automate graphic design?

Automate Graphic Design with PIL

In another article, I share the issues implementation managers face when setting up a new warehouse facility.

A photograph of a pallet location in a warehouse, focusing on a yellow highlighted barcode label on the shelf. The label includes a code and identification details. Above the shelf are stacked boxes, and a blue line visually highlights the label’s position, aiding in the identification of storage locations.
Example of Warehouse Label for a Pallet Location — (Image by Author)

They must manually create hundreds of labels for racks, shelves and workstations.

Automatically Generated Labels — (Image by Author)
Can we automate this process?

Instead of generating graphs, you can create visuals, illustrations, or labels, as in the example below.

These labels have been automatically generated by a Python script using the PIL library.

A diagram illustrating a workflow to generate warehouse labels using Python. An Excel file is used to create labels through Python scripts. The process generates barcodes and stickers for different warehouse locations, with each label displaying a unique number, directional arrow, and product information like clothing items or packaging.
Workflow — (Image by Author)

Using Python, I designed a completely automated workflow to generate labels based on parameters stored in an Excel file.

If you want to implement it, check the details 👇

Automate Graphic Design using Python
Use Python Pillow to automate the creation of hundred warehouse labels for the signage of picking locations

If you prefer, you can watch the video version of this tutorial,

About Me

Let’s connect on Linkedin and Twitter. I am a Supply Chain Engineer who uses data analytics to improve logistics operations and reduce costs.

For consulting or advice on analytics and sustainable supply chain transformation, feel free to contact me via Logigreen Consulting.