Home > Backend Development > Python Tutorial > How Can I Efficiently Update Matplotlib Plots with New Data?

How Can I Efficiently Update Matplotlib Plots with New Data?

Linda Hamilton
Release: 2024-12-05 18:38:12
Original
279 people have browsed it

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:

  1. Call graph1.clear() and graph2.clear() to remove the current data.
  2. Recalculate and plot the new data as before.

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:

  1. Modifying your code to separate the plotting logic from the data acquisition logic.
  2. Ensuring that the data shape remains constant.
  3. Manually resetting the x and y axis limits if the data range changes.

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()
Copy after login

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!

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