Issue
I am trying to animate a simple patches.Rectangle object using matplotlib. I want to plot the path traced by the said object (or the area swiped by it) in the animation. I could see that people are tracing paths of a single particle by appending all its previous positions to a list, but I am not sure how to do that for, say, a Rectangle .
One way to do that (I guess) would be to plot the Rectangle in the new positions without wiping out the Rectangle from the previous frames. But I don't know how to do that.
I am using the following code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import animation
# x and y go from 0 to 1 in 100 steps
x = [i/100 for i in range(100)]
y = [i/100 for i in range(100)]
# Angle goes from 0 to pi/2 in 100 steps
orientation = [(1.57)*i/100 for i in range(100)]
fig = plt.figure()
plt.axis('equal')
plt.grid()
ax = fig.add_subplot(111)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
patch = patches.Rectangle((0, 0), 0, 0, fc='r')
def init():
ax.add_patch(patch)
return patch,
def animate(i):
patch.set_width(5.0)
patch.set_height(2.0)
patch.set_xy([x[i], y[i]])
patch.angle = np.rad2deg(orientation[i])
return patch,
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(x),
interval=5, blit=True, repeat_delay=500)
plt.show()
In other words, I want to see the trace of the rectangle as it moves in addition to just the rectangle moving. Ideally, the solution should be easily applicable to other patches objects (Polygon, Ellipse, etc.) also.
Solution
To keep the object in the animation, you don't need to initialize it, just add the object to an empty list, specify it as Patch_collection, and set it to add_collection(). I believe this can be diverted to other objects as well; a reference example of PatchCollection can be found here.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import animation
from matplotlib.collections import PatchCollection
# x and y go from 0 to 1 in 100 steps
x = [i/100 for i in range(100)]
y = [i/100 for i in range(100)]
# Angle goes from 0 to pi/2 in 100 steps
orientation = [(1.57)*i/100 for i in range(100)]
fig = plt.figure()
plt.axis('equal')
plt.grid()
ax = fig.add_subplot(111)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
patch = patches.Rectangle((0, 0), 0, 0, fc='r')
def init():
ax.add_patch(patch)
return patch,
items = []
def animate(i):
patch.set_width(5.0)
patch.set_height(2.0)
patch.set_xy([x[i], y[i]])
patch.angle = np.rad2deg(orientation[i])
items.append(patch)
fig = ax.add_collection(PatchCollection(items, fc='r', ec='white', alpha=x[i]))
return fig,
anim = animation.FuncAnimation(fig, animate, frames=len(x), interval=200, blit=True, repeat=False)
plt.show()
Answered By - r-beginners
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.