Home >Backend Development >Python Tutorial >How Can I Achieve Real-Time Plotting Within a While Loop in Python?
Developers frequently encounter the challenge of plotting data in real-time as part of data-driven applications. However, a common issue arises when attempting to implement real-time plotting within a "while" loop.
Consider the following example, where we aim to plot random data points in real-time using OpenCV:
fig = plt.figure() plt.axis([0, 1000, 0, 1]) i = 0 x = list() y = list() while i < 1000: temp_y = np.random.random() x.append(i) y.append(temp_y) plt.scatter(i, temp_y) i += 1 plt.show()
Unfortunately, this code fails to plot the points individually in real-time. Instead, it pauses the execution of the program until the loop completes before displaying the graph.
The key to enabling real-time plotting lies in calling the plt.pause(0.05) function within the loop. This function not only updates the plot with the latest data but also runs the GUI's event loop. This allows for user interaction, ensuring that the plot remains responsive and interactive during the execution of the loop:
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()
By incorporating plt.pause(0.05), you unlock the ability to plot data points in real-time, allowing you to visualize your data as it streams in.
The above is the detailed content of How Can I Achieve Real-Time Plotting Within a While Loop in Python?. For more information, please follow other related articles on the PHP Chinese website!