How to Create Real-time Dynamic Plots in Matplotlib?

Susan Sarandon
Release: 2024-11-24 04:56:13
Original
281 people have browsed it

How to Create Real-time Dynamic Plots in Matplotlib?

Dynamically Updating Plot in Matplotlib

Question:

How can I update a real-time plot in Python's Matplotlib library, adding data points as they become available?

Answer:

Matplotlib provides multiple methods for animating data in real time. One recommended approach for your scenario is to use the animation API function FuncAnimation. This function animates a function in time, where your function can be the one used to acquire data from the serial port.

Each animation method typically updates the data property of the drawn object. This property can be extended to preserve previous points while adding newer ones.

Given the uncertain data arrival time, you can implement a function like the following:

import matplotlib.pyplot as plt
import numpy

hl, = plt.plot([], [])

def update_line(hl, new_data):
    hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
    hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
    plt.draw()
Copy after login

Simply call update_line with the received data whenever a new data point is obtained from the serial port. This approach allows for dynamic plot updates without the need for clearing or redrawing the entire graph.

The above is the detailed content of How to Create Real-time Dynamic Plots 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