How to refresh text in Matplotlib?

To refresh text in Matplotlib, you can dynamically update text elements by modifying their content and redrawing the canvas. This is useful for creating interactive plots or animations where text needs to change based on user input or data updates.

Basic Text Refresh with Key Events

Here's how to refresh text based on keyboard input ?

import matplotlib.pyplot as plt

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

# Create figure and subplot
fig, ax = plt.subplots()
text = ax.text(0.5, 0.5, 'Press Z or C to change text', 
               horizontalalignment='center', fontsize=14)

def update_text(event):
    """Update text based on key press events"""
    if event.key == "z":
        text.set_text("Zoom mode activated!")
    elif event.key == "c":
        text.set_text("Cool feature enabled!")
    elif event.key == "r":
        text.set_text("Press Z or C to change text")
    
    # Refresh the canvas to show updated text
    fig.canvas.draw()

# Connect the key press event to our function
fig.canvas.mpl_connect('key_press_event', update_text)

plt.title("Interactive Text Refresh Demo")
plt.show()

Animated Text Refresh

You can also refresh text automatically using animation ?

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

fig, ax = plt.subplots()
text = ax.text(0.5, 0.5, '', horizontalalignment='center', fontsize=16)

messages = ["Loading...", "Processing data...", "Almost done...", "Complete!"]
counter = 0

def animate_text(frame):
    """Update text with each animation frame"""
    global counter
    text.set_text(messages[counter % len(messages)])
    counter += 1
    return [text]

# Create animation that updates every 1000ms (1 second)
anim = animation.FuncAnimation(fig, animate_text, frames=20, 
                              interval=1000, blit=True, repeat=True)

plt.title("Animated Text Refresh")
plt.show()

Real-time Data Text Updates

For updating text with real-time data or calculations ?

import matplotlib.pyplot as plt
import numpy as np
import time

fig, ax = plt.subplots()

# Create initial text elements
status_text = ax.text(0.5, 0.7, 'Status: Ready', 
                     horizontalalignment='center', fontsize=12)
counter_text = ax.text(0.5, 0.3, 'Count: 0', 
                      horizontalalignment='center', fontsize=12)

def refresh_display():
    """Simulate refreshing text with new data"""
    for i in range(5):
        status_text.set_text(f'Status: Processing... {i+1}/5')
        counter_text.set_text(f'Count: {i * 10}')
        
        # Force refresh the display
        fig.canvas.draw()
        plt.pause(0.5)  # Wait 0.5 seconds
    
    # Final update
    status_text.set_text('Status: Complete!')
    counter_text.set_text('Count: 50')
    fig.canvas.draw()

# Add a button click simulation
ax.text(0.5, 0.1, 'Click to start refresh demo', 
        horizontalalignment='center', fontsize=10, style='italic')

# Automatically start the demo after 1 second
plt.title("Real-time Text Refresh Demo")
fig.canvas.mpl_connect('button_press_event', lambda event: refresh_display())

plt.show()

Key Methods for Text Refresh

Method Purpose When to Use
text.set_text() Update text content Change displayed text
fig.canvas.draw() Redraw entire canvas Manual refresh needed
plt.pause() Brief pause with refresh Real-time updates
FuncAnimation Automatic refresh cycle Continuous animations

Conclusion

Text refresh in Matplotlib is achieved by using set_text() to update content and fig.canvas.draw() to refresh the display. Use event handlers for interactive updates or FuncAnimation for automated text changes.

Updated on: 2026-03-25T22:37:50+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements