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