How to pause a pylab figure until a key is pressed or mouse is clicked? (Matplotlib)

To pause a pylab figure until a key is pressed or mouse is clicked, we can use Matplotlib's event handling system with button_press_event and key_press_event.

Understanding Event Handling

Matplotlib provides an interactive event system that can detect mouse clicks and key presses. We can bind callback functions to these events to control the animation flow.

Basic Example: Mouse Click to Pause

Here's how to create an animated plot that pauses when you click the mouse ?

import matplotlib
matplotlib.use("TkAgg")  # Set backend before importing pyplot
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

plt.ion()  # Turn on interactive mode

fig = plt.figure()
pause = False

def onclick(event):
    global pause
    pause = not pause
    print(f"Animation {'paused' if pause else 'resumed'}")

# Bind the mouse click event
fig.canvas.mpl_connect('button_press_event', onclick)

# Create data
data = np.linspace(-10, 10, 100)
x = np.sin(data)
y = np.cos(data)

flag = 1

# Animation loop
for i in range(50):  # Limited loop for demo
    if not pause:
        if flag == 1:
            fig.clear()
            plt.plot(data, y, color='red', label='Cosine')
            plt.title('Click to Pause/Resume - Red: Cosine')
            flag = 0
        else:
            fig.clear()
            plt.plot(data, x, color='blue', label='Sine')
            plt.title('Click to Pause/Resume - Blue: Sine')
            flag = 1
        plt.legend()
    
    plt.pause(0.1)  # Small delay for animation
    fig.canvas.draw()

plt.show()

Enhanced Version: Key Press and Mouse Click

This version responds to both mouse clicks and key presses ?

import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np

plt.ion()

fig, ax = plt.subplots(figsize=(8, 4))
pause = False

def on_click_or_key(event):
    global pause
    pause = not pause
    status = "PAUSED" if pause else "RUNNING"
    ax.set_title(f"Animation Status: {status}")
    plt.draw()

# Bind both mouse and keyboard events
fig.canvas.mpl_connect('button_press_event', on_click_or_key)
fig.canvas.mpl_connect('key_press_event', on_click_or_key)

# Generate sample data
t = np.linspace(0, 4*np.pi, 100)
sine_wave = np.sin(t)
cosine_wave = np.cos(t)

wave_type = 0

# Animation loop
for frame in range(100):
    if not pause:
        ax.clear()
        
        if wave_type == 0:
            ax.plot(t, sine_wave, 'g-', linewidth=2, label='Sine Wave')
            ax.set_title("Press any key or click mouse to pause")
        else:
            ax.plot(t, cosine_wave, 'm-', linewidth=2, label='Cosine Wave')
            ax.set_title("Press any key or click mouse to pause")
        
        ax.set_ylim(-1.5, 1.5)
        ax.legend()
        ax.grid(True, alpha=0.3)
        wave_type = 1 - wave_type  # Toggle between 0 and 1
    
    plt.pause(0.2)
    
plt.show()

Comparison of Methods

Event Type Event Name Trigger Use Case
Mouse button_press_event Any mouse button Simple pause/resume
Keyboard key_press_event Any key press More accessible control
Both Combined handlers Mouse or keyboard Maximum flexibility

Key Points

  • Use matplotlib.use("TkAgg") before importing pyplot for proper event handling
  • Enable interactive mode with plt.ion()
  • Global variables help maintain state across event callbacks
  • Use plt.pause() instead of time.sleep() for smooth animation
  • Call plt.draw() or fig.canvas.draw() to update the display

Conclusion

Matplotlib's event system allows easy control over plot animations. Use button_press_event for mouse control and key_press_event for keyboard control to create interactive visualizations that pause and resume on user input.

Updated on: 2026-03-25T23:18:53+05:30

988 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements