use*_*1_1 4 python animation matplotlib python-2.7
目标是绘制一个多边形,然后水平平移它。这必须以动画形式显示。以下是我的代码:-
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()
Run Code Online (Sandbox Code Playgroud)
到目前为止plt.show(),我画了一个三角形然后显示它。此后,我暂停一下以模拟动画时间的流逝。然后我重新绘制三角形,但是当我要求matplotlib刷新绘图时,没有任何变化。我在哪里犯错误?
第二个问题,我不想重新绘制三角形,而是只想使用诸如set_patch但没有这样的方法来更新已经存在的三角形的顶点坐标。而我们确实使用set_ydata等来修改现有绘图并创建动画。如何使用某种设置方法来制作所需的运动动画?
在之前帖子的帮助下,我能够弄清楚如何做到这一点:-
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()
Run Code Online (Sandbox Code Playgroud)
这样,我们就可以使用set_xy平移多边形了。通过提供一种创建对象句柄并操作它们的方法,这也解决了本文中的问题。
| 归档时间: |
|
| 查看次数: |
3021 次 |
| 最近记录: |