Categories
Python Answers

How to update a plot in Python matplotlib?

Spread the love

Sometimes, we want to update a plot in Python matplotlib.

In this article, we’ll look at how to update a plot in Python matplotlib.

How to update a plot in Python matplotlib?

To update a plot in Python matplotlib, we can call draw to draw the plot.

For instance, we write

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)

plt.ion()

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

to create the subplot with add_subplot.

Then we call plot with the x and y values we created with linspace and the sine sin function called with x.

Then in the for loop, we call draw to draw the plot with the latest data.

Conclusion

To update a plot in Python matplotlib, we can call draw to draw the plot.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *