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

How Can I Achieve Real-Time Plotting of Data Within a While Loop in Matplotlib?

Susan Sarandon
Release: 2024-12-15 12:10:11
Original
397 people have browsed it

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

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

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!

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