简体   繁体   中英

animation to translate polygon using matplotlib

Goal is to draw a polygon, then translate it horizontally. This has to be shown as an animation. Following is my code:-

import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
import time
import numpy as np

verts = np.array([
    [0., -0.25],  
    [0.5, 0.],  
    [0., 0.25],  
    [0., -0.25]
    ])
codes = [Path.MOVETO,
         Path.LINETO,
         Path.LINETO,
         Path.CLOSEPOLY,
         ]

path = Path(verts, codes)

fig = plt.figure()
ax = fig.add_subplot(111)
patch = patches.PathPatch(path, facecolor='orange')
ax.add_patch(patch)
ax.set_xlim(-10,10)
ax.set_ylim(-10,10)
plt.show()
time.sleep(1)
verts[:,0]=verts[:,0]+3
path = Path(verts, codes)
patch = patches.PathPatch(path, facecolor='orange')
ax.add_patch(patch)
plt.draw()

Upto plt.show() , i draw a triangle and then show it. Thereafter i give a pause to simulate passage of time for animation. Then i redraw the triangle but when i ask matplotlib to refresh the plot, there is no change. Where am i making error?

Second question, instead of redrawing the triangle, i only wanted to update the vertex coordinates of the already existing triangle using a method such as set_patch but there is no such method. Whereas we do use set_ydata , etc. to modify existing plots and create animation. How to use some set method to animate the desired motion?

With help from an earlier post , I was able to figure out how to do this:-

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)

v= np.array([
    [0., -0.25],  
    [0.5, 0.],  
    [0., 0.25]
    ])

patch = patches.Polygon(v,closed=True, fc='r', ec='r')
ax.add_patch(patch)

def init():
    return patch,

def animate(i):
    v[:,0]+=i
    patch.set_xy(v)
    return patch,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 5), init_func=init,
                              interval=1000, blit=True)
plt.show()

This way, we can use set_xy to translate the polygon. This then also solves the issue in this post by providing a way to create handles to objects and manipulating them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM