Home >Backend Development >Python Tutorial >How to Achieve Real-Time Plotting in a Matplotlib While Loop?

How to Achieve Real-Time Plotting in a Matplotlib While Loop?

DDD
DDDOriginal
2024-12-06 04:33:17990browse

How to Achieve Real-Time Plotting in a Matplotlib While Loop?

Real-time Plotting in a While Loop with Matplotlib

In this question, the user attempts to plot data in real time using OpenCV and matplotlib. However, the real-time plotting is not working as intended. The user provides a simplified example where the plot doesn't populate points one at a time, but instead waits until the loop finishes.

To address this issue, we need to understand how matplotlib updates plots in real time. By default, matplotlib expects a function call to plt.show() to display the plot and then block until the plot window is closed. This behavior prevents the data from being plotted in real time.

The solution is to use the plt.pause() function. plt.pause(0.05) draws the new data, runs the GUI's event loop, and pauses the plot for 0.05 seconds. This allows the plot to update in real time and respond to mouse interactions.

Here's the modified code that successfully plots 10 points in real time:

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()

With this adjustment, the plot will now display each point as it is generated, allowing for real-time visualization.

The above is the detailed content of How to Achieve Real-Time Plotting in a Matplotlib While Loop?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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