28. 02. 2025 Charles Callaway Documentation

Explaining Your Content with Complex Animations, Part 3

Welcome back! Last time we looked at some concrete examples of animations where you can use math to animate large numbers of objects, field-like effects, or complex behavior.

Today let’s look at the principal barrier to using an animation you make (if it’s not a filled rectangle and if you want to put it in the foreground of a video, dynamic presentation, etc.) in one of your videos: transparency. To disambiguate for a bit, when I say “transparency” there are two separate concepts here:

  • Semi-transparent (moving) objects within the animation that may overlap each other, and you want to partially see one that’s behind another
  • A transparent background, so that you can see things that aren’t part of the animation behind the animation’s rectangle, typically the borders (like a transparent PNG)

Remember that we’re looking at animated GIFs, because almost all video containers don’t allow for transparent backgrounds.

Let’s look at an example animated GIF, using one of our animations from the previous post:

The first type of transparency lets us see snowflakes through each other, giving it a slight 3D effect. The background color is the black, and for most of the videos or web page animations we do, we ‘d like to remove the black and composite it over or behind other graphics so we only see snowflakes, not the black.

How do I know that an animated GIF has transparency? Composite it between other layers in PowerPoint or your favorite video editor that supports it:

Note that if you have semi-transparent objects with a transparent background, you’ll need to worry about anti-aliasing and color mixing.

Here we’ll focus on the second type of transparency, because in general the first type is easy, you can just use the function set_alpha(0<=float<=1) in matplotlib for any single object you’re trying to draw.

There are two approaches for the second type:

  • Set the background’s transparency directly in Python/Matplotlib
  • Set a unique background color, then use a separate graphics program to make that color transparent

Setting Background Transparency Directly in Matplotlib

The first approach is the easiest, in the sense that you only have to write a single Python program, but there are some problems you’ll have to work around. It’s currently not possible to use a single coding template that will guarantee a transparent background on any given animation while having no side effects.

If you try to just make the background transparent, sometimes the objects lose their transparency, sometimes only parts will be transparent like the graphing area, and sometimes it just seems to not work at all. (Note that I’m working with Python 3.9.7, numpy 1.21.2, pandas 1.5.3 and scipy 1.7.5).

Here’s a template that should work most of the time:

def update(frame):     # Called for each animation frame
    ax.clear()         # Clear previous objects
    ax.set_xlim(x1,x2) # Set the X axes
    ax.set_ylim(y1,y2) # Set the Y axes
    …                  # Draw all the frame elements
    return fig,

# Create the graph
fig, ax = plt.subplots()
# Set the background color to black
ax.set_facecolor('#000000')
# Make the margins smaller
fig.patch.set_visible(False) 

# Iterate through all frames via update(i), drawing them one by one
ani = animation.FuncAnimation(fig, update, frames=range(0, 400), repeat=True)
# Save the series of frames as an animated GIF
ani.save('snow_transparent.gif', fps=10) # Length in seconds is frames/fps

Setting Background Transparency Externally

The other possibility involves using a separate graphics program to change a specific color (the background color) in every frame to have an alpha level of 0.0. This approach is quite reliable, but you need to make sure (just as with a green screen) that the color you use in the background is not used for anything else.

A number of GUI-based and command line-based programs can do this, sometimes via a simple “green screen” effect. But many of them work on videos, not animated GIFs, and besides, who wouldn’t prefer a simple and free solution?

Since I already use the ImageMagick graphics processor for other reasons, I turned to it for transparency in animated GIFs as well. ImageMagick is a free, open-source graphics suite that only works on the command line. It’s especially suited to pipeline-style or repetitive conversions involving formats, sizes, colors, etc.

To adapt the example above in Python, you only need to add some “kwargs” (or “keyword arguments”) to the animation’s save line as shown here:

def update(frame):     # Called for each animation frame
    ax.clear()         # Clear previous objects
    ax.set_xlim(x1,x2) # Set the X axes
    ax.set_ylim(y1,y2) # Set the Y axes
    …                  # Draw all the frame elements
    return fig,

# Create the graph
fig, ax = plt.subplots()
# Make the margins smaller
fig.patch.set_visible(False) 

# Iterate through all frames via update(i), drawing them one by one
ani = animation.FuncAnimation(fig, update, frames=range(0, 400), repeat=True)
# Save the series of frames as an animated GIF
ani.save('snow.gif', fps=10, writer='imagemagick',
         savefig_kwargs={"transparent":"white", "facecolor":"#ffffff00"})

We then need to do a single post-processing step with ImageMagick:

C:...\Animations> convert snow.gif -set dispose background -transparent White snow_transparent.gif

Now you can run Python on your animation code, then in the same CLI run ImageMagick to convert it, and you’re done! The animated GIF with transparency is ready to be imported into your video editor.

Charles Callaway

Charles Callaway

Author

Charles Callaway

Leave a Reply

Your email address will not be published. Required fields are marked *

Archive