Home >Backend Development >Python Tutorial >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()
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!