Skip to content Skip to sidebar Skip to footer

How To Animate A Polygon (defined By Arrays) With Python & Matplotlib

Good day ! Problem explanation: I want to animate a Polygon which values I receive from an array (in my simple example it is a moving sqaure). I want to keep the Polygon's x-and y-

Solution 1:

Yes, you will need to create the Polygon first and add it to the axes. Inside the animating function you may use the patch's patch.set_xy() method to update the vertices of the polygon.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
import matplotlib.patches as patches

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(-10,10)
ax.set_ylim(-10,10)

P1x=[0.0,0.5,1.0,1.5,2.0,2.5,3.0]
P1y=[0.0,0.0,0.0,0.0,0.0,0.0,0.0]
P2x=[1.0,1.5,2.0,2.5,3.0,3.5,4.0]
P2y=[0.0,0.0,0.0,0.0,0.0,0.0,0.0]
P3x=[1.0,1.5,2.0,2.5,3.0,3.5,4.0]
P3y=[1.0,1.0,1.0,1.0,1.0,1.0,1.0]
P4x=[0.0,0.5,1.0,1.5,2.0,2.5,3.0]
P4y=[1.0,1.0,1.0,1.0,1.0,1.0,1.0]

P = np.concatenate((np.array([P1x, P2x, P3x, P4x]).reshape(4,1,len(P1x)),
                    np.array([P1y, P2y, P3y, P4y]).reshape(4,1,len(P1x))), axis=1)

patch = patches.Polygon(P[:,:,0],closed=True, fc='r', ec='r')
ax.add_patch(patch)

def init():
    return patch,

def animate(i):
    patch.set_xy(P[:,:,i])
    return patch,

ani = animation.FuncAnimation(fig, animate, np.arange(P.shape[2]), init_func=init,
                              interval=1000, blit=True)
plt.show()

Post a Comment for "How To Animate A Polygon (defined By Arrays) With Python & Matplotlib"