Matplotlib Animation Polygons

2019-06-11 23:13发布

Using matplotlib, I am trying to use the animate function with a polygon, to rotate it in the plane.

The code pasted below only draws the first polygon but the animation doesn't work.

Can someone spot what's wrong in the animate function?

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.patches import Polygon
fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(7, 6.5)

ax = plt.axes(xlim=(-30, 30), ylim=(-30, 30))


pts = [[0.,0.], [2.,0.], [9.6,7.6], [9.6,9.6]]


patch = plt.Polygon(pts,closed=None, fill=None, edgecolor='r')
def init():
    patch.pts = [[0.,0.], [2.,0.], [9.6,7.6], [9.6,9.6]]
    ax.add_patch(patch)
    return patch,

def animate(i):

    x1=0.+ 10. * np.sin(np.radians(i))
    x2=2.+ 10. * np.sin(np.radians(i))
    x3=9.6+ 10. * np.sin(np.radians(i))
    x4=9.6+ 10. * np.sin(np.radians(i))

    y1=0.+ 10. * np.cos(np.radians(i))
    y2=0.+ 10. * np.cos(np.radians(i))
    y3=7.6+ 10. * np.cos(np.radians(i))
    y4=9.6+ 10. * np.cos(np.radians(i))


    patch.pts = [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]


    return patch,


anim = animation.FuncAnimation(fig,animate,init_func=init,frames=36,interval=1000,blit=True)


plt.show()

1条回答
▲ chillily
2楼-- · 2019-06-11 23:51

The line:

patch.pts = [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]

does not update the vertices of the polygon. You can use set_xy to change the vertices:

patch.set_xy([[x1,y1], [x2,y2], [x3,y3], [x4,y4]])

This will make the plot change on each iteration. The Matplotlib artists documentation has more information.

It still doesn't look like the shape is rotating. That's something to do with the coordinates you're using.

查看更多
登录 后发表回答