How to set timeout to pyplot.show() in Matplotlib?

To set timeout to pyplot.show() in Matplotlib, you can use the figure's built-in timer functionality. This automatically closes the plot window after a specified duration.

Basic Timeout Implementation

Here's how to create a plot that closes automatically after 5 seconds ?

import matplotlib.pyplot as plt

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

fig = plt.figure()

# Set the timer interval to 5000 milliseconds (5 seconds)
timer = fig.canvas.new_timer(interval=5000)
timer.add_callback(plt.close)

plt.plot([1, 2, 3, 4, 5])
plt.ylabel('Y-axis Data')

timer.start()
plt.show()

How It Works

The process involves three key steps:

  • Create a timer: Use fig.canvas.new_timer() to create a backend-specific timer object
  • Add callback: Use timer.add_callback(plt.close) to specify what happens when timer expires
  • Start timer: Call timer.start() before plt.show() to begin countdown

Customizable Timeout Function

For reusability, you can create a function that accepts timeout duration ?

import matplotlib.pyplot as plt

def show_with_timeout(timeout_ms=3000):
    """Display plot with automatic timeout"""
    fig = plt.gcf()  # Get current figure
    timer = fig.canvas.new_timer(interval=timeout_ms)
    timer.add_callback(plt.close)
    timer.start()
    plt.show()

# Example usage
plt.plot([1, 2, 3, 4, 5], [2, 4, 1, 5, 3])
plt.title('Plot with 3-second timeout')
show_with_timeout(3000)  # 3 seconds

Multiple Plots with Different Timeouts

You can set different timeout values for multiple plots ?

import matplotlib.pyplot as plt
import numpy as np

# First plot - 2 seconds
fig1 = plt.figure()
timer1 = fig1.canvas.new_timer(interval=2000)
timer1.add_callback(lambda: plt.close(fig1))

plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.title('Closes in 2 seconds')
timer1.start()
plt.show()

# Second plot - 4 seconds  
fig2 = plt.figure()
timer2 = fig2.canvas.new_timer(interval=4000)
timer2.add_callback(lambda: plt.close(fig2))

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.title('Closes in 4 seconds')
timer2.start()
plt.show()

Key Points

  • Timer interval is specified in milliseconds (1000ms = 1 second)
  • The timer must be started before calling plt.show()
  • Use lambda functions for specific figure targeting in multiple plots
  • The window closes automatically without user interaction

Conclusion

Use fig.canvas.new_timer() with plt.close callback to automatically close matplotlib plots after a timeout. This is useful for automated scripts or demonstrations where plots should display temporarily.

Updated on: 2026-03-25T23:47:24+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements