Home > Backend Development > Python Tutorial > How Can I Achieve Real-Time Plotting Within a While Loop in Python?

How Can I Achieve Real-Time Plotting Within a While Loop in Python?

Linda Hamilton
Release: 2024-12-08 00:24:16
Original
336 people have browsed it

How Can I Achieve Real-Time Plotting Within a While Loop in Python?

Plotting in Real-Time Within While Loops

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()
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template