Home >Backend Development >Python Tutorial >How Can I Efficiently Update Matplotlib Plots with New Data?
Updating Plots in Matplotlib
When working with interactive plots in Matplotlib, it's often necessary to update the plot with new data. This can be achieved in two ways:
Option 1: Clear and Replot
This approach involves clearing the existing plot and redrawing it from scratch. To do this:
While this method is simple, it's also the slowest.
Option 2: Update Data
To avoid replotting the entire graph, you can directly update the data of the existing plot objects. This is much faster, but requires:
Example:
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 6*np.pi, 100) y = np.sin(x) fig = plt.figure() ax = fig.add_subplot(111) line1, = ax.plot(x, y, 'r-') for phase in np.linspace(0, 10*np.pi, 500): line1.set_ydata(np.sin(x + phase)) fig.canvas.draw() fig.canvas.flush_events()
The above is the detailed content of How Can I Efficiently Update Matplotlib Plots with New Data?. For more information, please follow other related articles on the PHP Chinese website!