Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to update the matplotlib plot without closing the window?

I'm completely new to matplotlib and decently experienced but rusty with python and I'm struggling to work with matplotlib currently. I'm trying to kind of animate a point on the plot, kind of like this: https://www.desmos.com/calculator/rv8gbimhon

I've written the code for it but the plot doesn't update the point in real time during the while loop, instead, the while loop is paused until I close the plot window and the next iteration of the loop happens, re-opening the plot with the updated coords. Is there a way to move a point on matplotlib without opening and closing windows?

My code:

import numpy as np
import time
t = 0
start_time = time.time()
while t < 30:
    end_time = time.time()
    t = end_time - start_time
    print(t)
    plt.plot(t,t,"g^")
    plt.show()
like image 665
Mixnik Avatar asked Oct 25 '25 02:10

Mixnik


1 Answers

One option to update the plot in a loop is to turn on interactive mode and to update the plot using pause.

For example:

import numpy as np
import matplotlib.pyplot as plt
import time

point = plt.plot(0, 0, "g^")[0]
plt.ylim(0, 5)
plt.xlim(0, 5)
plt.ion()
plt.show()

start_time = time.time()
t = 0
while t < 4:
    end_time = time.time()
    t = end_time - start_time
    print(t)
    point.set_data(t, t)
    plt.pause(1e-10)

However, for more advanced animation I would propose to use the animation class.

like image 65
insulanus Avatar answered Oct 26 '25 20:10

insulanus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!