使用matplotlib转换多边形的动画 [英] animation to translate polygon using matplotlib

查看:94
本文介绍了使用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()

最多 plt.show( ),我画了一个三角形然后显示出来。此后,我暂停一下以模拟动画的时间流逝。然后我重新绘制三角形,但是当我要求 matplotlib 刷新图时,没有任何变化。我在哪里出错?

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?

第二个问题,而不是重新绘制三角形,我只想使用诸如<$这样的方法来更新已经存在的三角形的顶点坐标。 c $ c> set_patch ,但没有这种方法。而我们确实使用 set_ydata 等来修改现有图并创建动画。

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()

这样,我们可以使用 set_xy 来转换多边形。然后,这也通过提供一种创建对象的句柄并对其进行操作的方式来解决本文中的问题。

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.

这篇关于使用matplotlib转换多边形的动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆