Reputation: 5793
I would like to create an animation with matplotlib in python. As the animated data is function of two parameter (time, number of bodies) I got an idea to use 2 for loops. The code is below:
import time
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import pylab as plb
# set up figure for plotting:
fig = plt.figure()
ax = fig.add_subplot(111)
# plot limits
ax.set_xlim(-(max(q0) + bodies[-1].L), +(max(q0) + bodies[-1].L))
ax.set_ylim(-(max(q0) + bodies[-1].L), +(max(q0) + bodies[-1].L))
# colors
colors = ['b', 'g', 'c']
for i_t in range(0, np.shape(t)[1]): #t is an one column matrix
for i in range(0, N):
ax.plot(x_matrix[i_t, i], y_matrix[i_t, i], 's', color=colors[i])
plt.draw()
plt.show()
The problem is that the code generates me one plot but with all animated points. I would like to have the animation ploted for one time value (counter i_t) and all bodies (counter i) in one window as a movie so the previous plot is erased at the next time step.
I have changed the code you suggested to:
for i_t in range(0, np.shape(t)[1]):
for i in range(0, N):
ax.clear()
ax.plot(x_matrix[i_t, i], y_matrix[i_t, i], 's', color=colors[i])
plt.pause(0.001)
plt.draw()
But then I get an error:
C:\Python27\lib\site-packages\matplotlib\backend_bases.py:2292: MatplotlibDeprecationWarning: Using default event loop until function specific to this GUI is implemented warnings.warn(str, mplDeprecation)
That isn't so frightening but when running the code the points that would have to be plotted together (counter i) are plotted apart so it looks like blinkig dots (if you know what I mean).
Any suggestions. I think I am close to the solution, but still need the finishig touch for the code to be working. I hope this can be done the way I imagined so I would not have to solve the problem with different approach.
Upvotes: 1
Views: 13850
Reputation: 5793
I have solved the problem. The solution is (if anyone will need it):
for i_t in range(0, np.shape(t)[1]):
ax.clear()
plt.hold(True)
# plot limits
ax.set_xlim(-(max(q0) + bodies[-1].L), +(max(q0) + bodies[-1].L))
ax.set_ylim(-(max(q0) + bodies[-1].L), +(max(q0) + bodies[-1].L))
for i in range(0, N):
ax.plot(x_matrix[i_t, i], y_matrix[i_t, i], 's', color=colors[0, i])
plt.pause(0.0001)
I would have posted earlyer, but as a new user I had to wait for 8 hours to answer my own question.
Upvotes: 3
Reputation: 85432
Change the last section of your code to this:
for i_t in range(np.shape(t)[1]): #t is an one column matrix
for i in range(N):
ax.clear()
ax.plot(x_matrix[i_t, i], y_matrix[i_t, i], 's', color=colors[i])
plt.pause(0.001)
# eof
Adapt the animation speed by changing the number in plt.pause(0.001)
.
Upvotes: 2