How to animate text in Matplotlib?

Text animation in Matplotlib allows you to create dynamic visual effects by changing text properties over time. This is useful for presentations, data storytelling, and creating engaging visualizations.

Basic Text Animation Setup

To animate text in matplotlib, we need to import the animation module and set up a figure with an axes object. The animation works by repeatedly calling a function that modifies text properties.

Example

Here's how to create an animated text that changes color and size over time −

from matplotlib import animation
import matplotlib.pyplot as plt

# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create figure and axes
fig = plt.figure()
ax = fig.add_subplot(111)

# Initialize text
text = 'You are welcome!'
txt = ax.text(0.20, 0.5, text, fontsize=15)

# Define colors for animation
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', 
          '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

def animate(num):
    # Change font size and color
    txt.set_fontsize(num * 2 + num)
    txt.set_color(colors[num % len(colors)])
    return txt,

# Create animation
anim = animation.FuncAnimation(fig, animate, frames=len(text) - 1, blit=True)

plt.show()

How It Works

The animation function modifies two text properties −

  • Font size − Increases based on the frame number using num * 2 + num
  • Color − Cycles through the colors list using modulo operator
  • Frames − Animation runs for len(text) - 1 frames
  • Blit − Optimizes performance by only redrawing changed parts

Customizing Text Animation

You can modify various text properties for different effects −

from matplotlib import animation
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

txt = ax.text(0.5, 0.5, 'Animated Text', fontsize=20, ha='center')

def animate(frame):
    # Animate position, size, and rotation
    x = 0.5 + 0.2 * np.sin(frame * 0.2)
    y = 0.5 + 0.1 * np.cos(frame * 0.3)
    size = 20 + 10 * np.sin(frame * 0.1)
    rotation = frame * 2
    
    txt.set_position((x, y))
    txt.set_fontsize(size)
    txt.set_rotation(rotation)
    
    return txt,

anim = animation.FuncAnimation(fig, animate, frames=200, interval=50, blit=True)
plt.show()

Key Parameters

Parameter Description Example
frames Number of animation frames 100, len(text)
interval Delay between frames (ms) 50, 100
blit Performance optimization True, False
repeat Loop animation True, False

Conclusion

Text animation in Matplotlib is achieved using FuncAnimation to repeatedly modify text properties like position, size, color, and rotation. Use blit=True for better performance in complex animations.

Updated on: 2026-03-26T02:31:31+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements