Animated Visualization with GIF Export

Given a dataset showcasing daily sales over a year, create an animated line chart that visualizes sales accumulating day by day. Additionally, export this animation as a .gif file.

NOTE:

This code will not run on Trinket ENV but should work perfectly fine on Jupyter lab of your local ENV or Google Colab if you have matplotlib python package installed.

Example Output:

You’ll need the FuncAnimation class from the matplotlib.animation module and PillowWriter for exporting to GIF.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter

def animate(i):
    ax.clear()
    ax.plot(daily_sales[:i+1], color='blue')
    plt.xlabel("Days")
    plt.ylabel("Sales")
    plt.title("Daily Sales Over a Year")
    plt.grid(True)

daily_sales = [50, 55, 54, 52, 53, 60, 62, 58, 59, 65, 66, 68] * 30
fig, ax = plt.subplots(figsize=(10, 6))

ani = FuncAnimation(fig, animate, frames=len(daily_sales), repeat=False)

# Save the animation as a .gif file
writer = PillowWriter(fps=20)
ani.save("daily_sales.gif", writer=writer)

plt.show()

The above-shared code will generate a huge GIF file in terms of size. Here is the code that will generate a more optimized version of the GIF file.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter

def animate(i):
    ax.clear()
    ax.plot(averaged_sales[:i+1], color='blue')
    plt.xlabel("Days")
    plt.ylabel("Sales")
    plt.title("Averaged Daily Sales Over a Year")
    plt.grid(True)

daily_sales = [50, 55, 54, 52, 53, 60, 62, 58, 59, 65, 66, 68] * 30

# Take an average of sales every 5 days
averaged_sales = [sum(daily_sales[i:i+5])/5 for i in range(0, len(daily_sales), 5)]

fig, ax = plt.subplots(figsize=(5, 3)) # Reduced figure size

ani = FuncAnimation(fig, animate, frames=len(averaged_sales), repeat=False)

# Save the animation as a .gif file with reduced FPS
writer = PillowWriter(fps=10) # Reduced FPS without DPI
ani.save("averaged_daily_sales.gif", writer=writer)

plt.show()

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!