Python中的箭头动画

4

首先,我刚开始学习Python。在过去的几个小时里,我一直在努力尝试更新箭头属性,以便在绘制动画期间更改它们。

在彻底寻找答案之后,我发现可以通过修改“center”属性(例如 circle.center = new_coordinates)来更改圆形补丁中心。然而,我不知道如何将此机制推广到箭头补丁中...

目前的代码为:

import numpy as np, math, matplotlib.patches as patches
from matplotlib import pyplot as plt
from matplotlib import animation

# Create figure
fig = plt.figure()    
ax = fig.gca()

# Axes labels and title are established
ax = fig.gca()
ax.set_xlabel('x')
ax.set_ylabel('y')

ax.set_ylim(-2,2)
ax.set_xlim(-2,2)
plt.gca().set_aspect('equal', adjustable='box')

x = np.linspace(-1,1,20) 
y  = np.linspace(-1,1,20) 
dx = np.zeros(len(x))
dy = np.zeros(len(y))

for i in range(len(x)):
    dx[i] = math.sin(x[i])
    dy[i] = math.cos(y[i])
patch = patches.Arrow(x[0], y[0], dx[0], dy[0] )


def init():
    ax.add_patch(patch)
    return patch,

def animate(t):
    patch.update(x[t], y[t], dx[t], dy[t])   # ERROR
    return patch,

anim = animation.FuncAnimation(fig, animate, 
                               init_func=init, 
                               interval=20,
                               blit=False)

plt.show()

尝试了几个选项后,我认为更新功能可以在某种程度上让我更接近解决方案。然而,我遇到了一个错误:

TypeError: update() takes 2 positional arguments but 5 were given

如果我按照下面所示的定义animate函数的方式,每一步只添加一个补丁,则会得到附图所示的结果。

def animate(t):
    patch = plt.Arrow(x[t], y[t], dx[t], dy[t] )
    ax.add_patch(patch)
    return patch,

错误的动画

我尝试添加了一个patch.delete语句并创建了一个新的patch作为更新机制,但结果是一个空动画...


小贴士:如果你真的是一个初学者,我建议你先尝试一些简单得多的东西,然后再去尝试类似这样的项目。 - Christian Dean
1
你可能是对的…我已经成功实现了2D和3D动画,包括线条和散点,而我只是想更进一步。学会更新动画中的任意对象将开启一个全新的世界:P 感谢这个提示! - J. Berzosa
很高兴能帮到你,伙计! - Christian Dean
2个回答

3
ax.add_patch(patch)之前添加ax.clear(),但这将从图中删除所有元素。
def animate(t):

    ax.clear() 

    patch = plt.Arrow(x[t], y[t], dx[t], dy[t] )
    ax.add_patch(patch)

    return patch,

编辑:移除一个补丁

  • using ax.patches.pop(index).

    In your example is only one patch so you can use index=0

      def animate(t):
    
          ax.patches.pop(0) 
    
          patch = plt.Arrow(x[t], y[t], dx[t], dy[t] )
          ax.add_patch(patch)
    
          return patch,
    
  • using ax.patches.remove(object)

    It needs global to get/set external patch with Arrow

      def animate(t):
    
          global patch
    
          ax.patches.remove(patch) 
    
          patch = plt.Arrow(x[t], y[t], dx[t], dy[t] )
          ax.add_patch(patch)
    
          return patch,
    

顺便提一下:获取您可以与 update() 一起使用的属性列表。

print( patch.properties().keys() )

dict_keys(['aa', 'clip_path', 'patch_transform', 'edgecolor', 'path', 'verts', 'rasterized', 'linestyle', 'transform', 'picker', 'capstyle', 'children', 'antialiased', 'sketch_params', 'contains', 'snap', 'extents', 'figure', 'gid', 'zorder', 'transformed_clip_path_and_affine', 'clip_on', 'data_transform', 'alpha', 'hatch', 'axes', 'lw', 'path_effects', 'visible', 'label', 'ls', 'linewidth', 'agg_filter', 'ec', 'facecolor', 'fc', 'window_extent', 'animated', 'url', 'clip_box', 'joinstyle', 'fill'])

您可以使用update更改颜色- facecolor

def animate(t):
    global patch
    
    t %= 20 # get only 0-19 to loop animation and get color t/20 as 0.0-1.0

    ax.patches.remove(patch)

    patch = patches.Arrow(x[t], y[t], dx[t], dy[t])

    patch.update({'facecolor': (t/20,t/20,t/20,1.0)})
    
    ax.add_patch(patch)

    return patch,

1

我通过模仿patches.Arrow.__init__中的代码找到了这个:

import numpy as np
import matplotlib.patches as patches
from matplotlib import pyplot as plt
from matplotlib import animation
import matplotlib.transforms as mtransforms

# Create figure
fig, ax = plt.subplots()

# Axes labels and title are established
ax.set_xlabel('x')
ax.set_ylabel('y')

ax.set_ylim(-2,2)
ax.set_xlim(-2,2)
ax.set_aspect('equal', adjustable='box')

N = 20
x = np.linspace(-1,1,N) 
y  = np.linspace(-1,1,N) 
dx = np.sin(x)
dy = np.cos(y)

patch = patches.Arrow(x[0], y[0], dx[0], dy[0])

def init():
    ax.add_patch(patch)
    return patch,

def animate(t):
    L = np.hypot(dx[t], dy[t])

    if L != 0:
        cx = float(dx[t]) / L
        sx = float(dy[t]) / L
    else:
        # Account for division by zero
        cx, sx = 0, 1

    trans1 = mtransforms.Affine2D().scale(L, 1)
    trans2 = mtransforms.Affine2D.from_values(cx, sx, -sx, cx, 0.0, 0.0)
    trans3 = mtransforms.Affine2D().translate(x[t], y[t])
    trans = trans1 + trans2 + trans3
    patch._patch_transform = trans.frozen()
    return patch,

anim = animation.FuncAnimation(fig, animate, 
                               init_func=init, 
                               interval=20,
                               frames=N,
                               blit=False)

plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接