【问题标题】:animation to translate polygon using matplotlib使用 matplotlib 翻译多边形的动画
【发布时间】:2016-11-15 10:53:10
【问题描述】:

目标是绘制一个多边形,然后水平平移它。这必须显示为动画。以下是我的代码:-

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 刷新绘图时,没有任何变化。我在哪里出错了?

第二个问题,我不想重绘三角形,只想用set_patch之类的方法更新已经存在的三角形的顶点坐标,但没有这样的方法。而我们确实使用set_ydata 等来修改现有的情节并创建动画。如何使用一些设置方法来制作所需的动画?

【问题讨论】:

    标签: python python-2.7 animation matplotlib


    【解决方案1】:

    earlier post 的帮助下,我能够弄清楚如何做到这一点:-

    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 post 中的问题,提供了一种创建对象句柄并对其进行操作的方法。

    【讨论】:

    • 我编辑了代码并删除了将补丁多次添加到轴的部分。这是完全没有必要的。
    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 2017-09-12
    • 2015-08-11
    • 2020-07-29
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多