Reputation: 45
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()
Upvotes: 4
Views: 9101
Reputation: 271
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.
Upvotes: 8