Home >Backend Development >Python Tutorial >How Can I Achieve Real-Time Plotting of Data Within a While Loop in Matplotlib?
Real-Time Plotting within a While Loop
When attempting to display data from a video source in real time, users often encounter difficulties in updating the plot within a while loop. One typical issue is that the plot remains static until the loop completes. This issue stems from the method used to display dynamic data.
In the provided code snippet:
while i < 1000: temp_y = np.random.random() x.append(i) y.append(temp_y) plt.scatter(i, temp_y) i += 1 plt.show()
The loop appends data points, plots a single point, and then calls plt.show(). However, plt.show() blocks the GUI and prevents other code from running until the window is manually closed, resulting in delayed updates.
To achieve real-time plotting, it's necessary to use plt.pause(). Here's a revised version:
import numpy as np import matplotlib.pyplot as plt plt.axis([0, 10, 0, 1]) for i in range(10): y = np.random.random() plt.scatter(i, y) plt.pause(0.05) plt.show()
The key change is the addition of plt.pause(0.05) after plotting each point. plt.pause() both draws the updated data and runs the GUI's event loop. The 0.05 argument specifies a delay of 50 milliseconds, giving the GUI time to display the point and handle user interactions (e.g., closing the window).
This modified code should ensure that the plot updates smoothly in real time, allowing the user to visualize the data dynamically.
The above is the detailed content of How Can I Achieve Real-Time Plotting of Data Within a While Loop in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!