Home > Backend Development > Python Tutorial > How to Dynamically Update Matplotlib Plots without Complete Redraws?

How to Dynamically Update Matplotlib Plots without Complete Redraws?

Patricia Arquette
Release: 2024-11-13 16:39:02
Original
418 people have browsed it

How to Dynamically Update Matplotlib Plots without Complete Redraws?

Dynamically Updating Plots in Matplotlib without Complete Redraws

When collecting data from a serial port and plotting it, there are inefficiencies associated with common update methods. Clearing and redrawing the entire plot or using timed animations may be impractical or introduce delays. This article presents an alternative approach that allows for incremental plot updates only when new data is received.

Incremental Plot Updates

Matplotlib provides a variety of animation techniques, including the FuncAnimation function. This function enables the animation of a specific function over time. In our case, we can use this function to animate the data acquisition process.

Implementing the Update Function

The animation method involves modifying the "data" property of the plotted object. Instead of clearing the screen or figure, we can simply extend the data property by appending new data points to existing ones. Here's an example function that does this:

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

When new data arrives from the serial port, simply call the update_line function with the new data. This will incrementally update the plot without incurring the overhead of redrawing the entire figure.

The above is the detailed content of How to Dynamically Update Matplotlib Plots without Complete Redraws?. 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