Categories
Python Answers

How to dynamically update plot in Python matplotlib?

Spread the love

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

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

How to dynamically update plot in Python matplotlib?

To dynamically update plot in Python matplotlib, we can call draw after we updated the plot data.

For instance, we write

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

to define the update_line function.

In it, we call set_xdata to set the data form the x-axis.

And we call set_ydata to do the same for the y-axis.

Then we call plt.draw to redraw the plot with the new data.

Conclusion

To dynamically update plot in Python matplotlib, we can call draw after we updated the plot data.

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 *