I’ve been working with Python for over a decade, and one of the libraries I frequently turn to for data visualization is Matplotlib. When you’re dealing with dynamic data, think stock prices in New York or live weather updates in Chicago, updating your plots in real-time becomes essential.
However, updating Matplotlib plots inside loops can be tricky if you don’t know the right approach. In this guide, I’ll walk you through practical methods for updating your plots within a loop effectively.
Methods to Update Plots in a Loop
Imagine you are tracking daily sales across multiple retail stores in the USA. You want to see how sales evolve minute by minute. Static plots won’t suffice here; you need your graph to update as new data streams in. This is where updating plots in a loop shines.
Matplotlib doesn’t automatically refresh plots inside loops, so if you just redraw the plot every iteration, it can flicker or slow down. Efficient updating techniques avoid these issues.
Check out Add Text to Plot Matplotlib in Python
1: Use plt.pause() to Update the Plot
One of the simplest ways to update a plot inside a loop is by using the plt.pause() function in Python. It briefly pauses the execution, allowing the plot to refresh.
Here’s an example that simulates live temperature readings from a weather station in Miami:
import matplotlib.pyplot as plt
import numpy as np
import time
plt.ion() # Turn on interactive mode
x = []
y = []
fig, ax = plt.subplots()
line, = ax.plot(x, y, 'r-') # Initialize an empty line plot
for i in range(50):
x.append(i)
y.append(np.random.uniform(75, 95)) # Simulated temperature in °F
line.set_xdata(x)
line.set_ydata(y)
ax.relim() # Recalculate limits
ax.autoscale_view() # Autoscale
plt.draw()
plt.pause(0.1) # Pause to update the plot
plt.ioff() # Turn off interactive mode
plt.show()I executed the above example code and added the screenshot below.

plt.ion()enables interactive mode, allowing the plot window to stay responsive.line.set_xdata()andline.set_ydata()update the data without redrawing the entire plot.plt.pause()gives the GUI event loop time to process the update.
This method is easy and works well for moderate update speeds.
Read Matplotlib Plot Error Bars
2: Clear and Redraw the Plot with plt.cla()
Another approach is to clear the axes and redraw the plot each iteration. This is less efficient but sometimes simpler for quick scripts.
Example simulating hourly traffic volume updates on a New York City highway:
import matplotlib.pyplot as plt
import numpy as np
import time
x = list(range(24)) # Hours in a day
plt.figure()
for _ in range(10):
y = np.random.randint(100, 1000, size=24) # Simulated traffic volume
plt.cla() # Clear current axes
plt.plot(x, y, label='Traffic Volume')
plt.xlabel('Hour')
plt.ylabel('Vehicles')
plt.title('NYC Highway Traffic Volume')
plt.legend()
plt.pause(1) # Pause for 1 second before next updateI executed the above example code and added the screenshot below.

- This method redraws the entire plot each time, which can cause flickering with large datasets or rapid updates.
- It’s best for simple or infrequent updates.
Check out Matplotlib Remove Tick Labels
3: Use FuncAnimation from Matplotlib’s Animation Module
For more control and smoother animations, FuncAnimation is the way to go. It handles updating the plot in the background and is ideal for real-time data visualization.
Here’s a practical example simulating live stock prices for a tech company on NASDAQ:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
x_data, y_data = [], []
line, = ax.plot([], [], 'b-')
ax.set_xlim(0, 50)
ax.set_ylim(100, 200)
ax.set_title('Live Stock Price - Tech Company')
ax.set_xlabel('Time (seconds)')
ax.set_ylabel('Price ($)')
def update(frame):
x_data.append(frame)
y_data.append(150 + np.random.randn()) # Simulated stock price
line.set_data(x_data, y_data)
if frame > 50:
ax.set_xlim(frame - 50, frame)
return line,
ani = FuncAnimation(fig, update, frames=range(100), interval=200, blit=True)
plt.show()I executed the above example code and added the screenshot below.

- It’s optimized for animations and real-time updates.
- You define an update function that modifies data efficiently.
blit=Trueimproves performance by only redrawing changed parts.
Read Plot Multiple Lines with Legends in Matplotlib
Tips for Efficient Plot Updates
- Avoid creating new figures or axes inside the loop. Initialize them once before the loop starts.
- Use
set_data()orset_xdata(),set_ydata()methods to update existing plot elements instead of redrawing everything. - Adjust axis limits dynamically using
relim()andautoscale_view()or by setting limits manually. - Turn on interactive mode (
plt.ion()) when using simple loops withplt.pause(). - For complex animations, prefer
FuncAnimationfor smoother visuals.
Updating Matplotlib plots in a loop opens up many possibilities for real-time data visualization, especially relevant for dynamic datasets like US economic indicators, weather monitoring, or live traffic feeds.
By choosing the right method, whether it’s plt.pause() for quick updates, clearing and redrawing for simplicity, or FuncAnimation for smooth animations, you can create effective visualizations that keep your audience engaged.
You may like to read:

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.