Plotting In A Non-Blocking Way With Matplotlib
Last Updated :
24 Apr, 2025
When we plot a graph with Matplotlib, by default the execution of the code is stopped/blocked when it is viewed/drawn until the view window is closed. However, in certain cases, one may want to remove this blocking behavior and see the graph as soon as it is plotted or updated without blocking the program execution. This article addresses this issue by showing how to plot with Matplotlib in a non-blocking way.
Note: This article assumes that the matplotlib.pyplot has been imported as plt. Hence, plt refers to matplotlib.pyplot everywhere in this article.
Plotting with Matplotlib in a non-blocking way
Plotting with Matplotlib such that the execution of the program is not halted on showing the graph window is called plotting in a non-blocking way. This may be required in several situations like plotting in an interactive console where one wants to plot the next graph only after having a look at the previous one, one wants to update the graph based on data, etc. In this section we will look at three ways to plot with Matplotlib in a non-blocking way -
- Using the "block" argument of plt.show() function.
- Using the plt.pause() function.
- Using the pyplot interactive mode (plt.ion()).
Using block argument of plt.show() function
In this approach, every time you want to see/update the plot, call the plt.show() function with the "block=False" argument. This will draw the latest updates on the window but not block the execution of the program afterward. After drawing the final graph, just call the plt.show() function without any arguments to halt the execution of the program at the point (because the program and hence the window will exit otherwise). This is demonstrated in the following example code -
Python3
import numpy as np
import matplotlib.pyplot as plt
def main():
# Set the axis limits for the plot
plt.axis([-50, 50, 0, 10000])
# Create an array of x values from -50 to 50
x = np.arange(-50, 51)
for power in range(1, 5):
# Calculate y values for x^power
y = [x_i ** power for x_i in x]
# Plot the function
plt.plot(x, y)
# Redraw the plot
plt.draw()
# Pause for a short duration to allow visualization
plt.pause(0.001)
# Wait for user input to continue
input("Press [Enter] to proceed to the next plot.")
if __name__ == '__main__':
# Enable interactive mode for non-blocking plotting
plt.ion()
# Display the plot window in non-blocking mode
plt.show(block=False)
main()
Output:

Using plt.pause() function
In this approach, when you want to show/update the plot, call the "plt.pause(n)" function where n is a decimal number denoting pause time in seconds. After the final plot, call the plt.show() function though because you would probably like to block the execution at this point otherwise the program would exit and so would the graph window. This is demonstrated with the following example -
Python3
import numpy as np
from matplotlib import pyplot as plt
def main():
plt.axis([-10, 10, -10, 10]) # Adjust axis limits for various functions
plt.ion()
plt.show()
x = np.arange(-10, 11)
# Plot different mathematical functions
for function_name in ["Linear", "Quadratic", "Cubic", "Square Root"]:
if function_name == "Linear":
y = x
elif function_name == "Quadratic":
y = x**2
elif function_name == "Cubic":
y = x**3
elif function_name == "Square Root":
y = np.sqrt(np.abs(x))
plt.plot(x, y, label=function_name)
plt.draw()
plt.pause(0.001)
input("Press [enter] to continue.")
if __name__ == '__main__':
main()
Output:
.gif)
Note that the graph gets updated before each pause. Moreover, we have used 1 second as the pause time for demonstration. One can make the pause time smaller (like 0.01 seconds) to reduce the pause time.
Using the pyplot interactive mode (plt.ion())
In this approach, we turn on the interactive mode of pyplot using plt.ion(). Once the interactive mode is turned on the plotting environment automatically gets into non-blocking mode and every time an update is made to the figure, it is instantly drawn. After all the plotting is done, it is recommended to turn off the interactive mode using plt.ioff() and then call plt.show() to block the program otherwise the program would exit and so would the matplotlib figure. This is demonstrated through the following example -
Python3
import matplotlib.pyplot as plt
import numpy as np
def plot_power(x, power):
y = x ** power
plt.plot(x, y)
plt.title(f'Plot of x^{power}')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.draw()
plt.pause(0.5)
def main():
x = np.arange(-50, 51)
powers = [1, 2, 3, 4]
plt.axis([-50, 50, 0, 10000])
plt.ion() # Turn on interactive mode
for power in powers:
plot_power(x, power)
input(f'Press [Enter] to proceed to the next plot (x^{power}).')
plt.ioff() # Turn off interactive mode
plt.show()
if __name__ == '__main__':
main()
Output:

Conclusion
We saw three different methods to plot in matplotlib in a non-blocking way. By default, the matplotlib has blocking behavior i.e., when a figure is drawn, it blocks the execution of the program until the figure window is closed. Although this is a useful feature most of the time, one may sometimes need to remove this behavior and plot in a non-blocking way. When plotting in a non-blocking way, the execution is not halted/blocked when the figure is drawn and further program can be executed keeping the figure window open. This is useful in situations like updating a graph or when we want to plot next graph only after looking at the previous one, etc.
Similar Reads
Introduction to 3D Plotting with Matplotlib
In this article, we will be learning about 3D plotting with Matplotlib. There are various ways through which we can create a 3D plot using matplotlib such as creating an empty canvas and adding axes to it where you define the projection as a 3D projection, Matplotlib.pyplot.gca(), etc. Creating an E
15+ min read
Plot a Point or a Line on an Image with Matplotlib
Prerequisites: Matplotlib Matplotlib and its constituents support a lot of functionality. One such functionality is that we can draw a line or a point on an image using Matplotlib in python. ApproachImport modulesRead the imagePlot the line or point on the imageDisplay the plot/image. Image Used: Im
2 min read
Matplotlib.pyplot.axvline() in Python
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. Note: For more inform
2 min read
matplotlib.pyplot.axhline() in Python
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.axhline() Function The axhline() function in pyplot module of matplotlib library is use
2 min read
How to plot a normal distribution with Matplotlib in Python?
Normal distribution, also known as the Gaussian distribution, is a fundamental concept in probability theory and statistics. It is a symmetric, bell-shaped curve that describes how data values are distributed around the mean. The probability density function (PDF) of a normal distribution is given b
4 min read
How to Create Subplots in Matplotlib with Python?
Matplotlib is a widely used data visualization library in Python that provides powerful tools for creating a variety of plots. One of the most useful features of Matplotlib is its ability to create multiple subplots within a single figure using the plt.subplots() method. This allows users to display
6 min read
How to update a plot in Matplotlib?
In this article, let's discuss how to update a plot in Matplotlib. Updating a plot simply means plotting the data, then clearing the existing plot, and then again plotting the updated data and all these steps are performed in a loop. Functions Used:canvas.draw(): It is used to update a figure that h
2 min read
How to Display an OpenCV image in Python with Matplotlib?
The OpenCV module is an open-source computer vision and machine learning software library. It is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and vide
2 min read
Matplotlib.pyplot.ion() in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.pyplot.ion() is used to turn on interactive mode. To check the status of
4 min read
Matplotlib.pyplot.hlines() in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. Matplotlib.pyplot.hlines() The Matplotlib.pyplot.hlines() is used to draw horizontal lin
2 min read