如何使用matplotlib动画使箭头 Flink 而不改变其位置?

lztngnrs  于 2023-06-30  发布在  Flink
关注(0)|答案(1)|浏览(181)

我是python的新手,但似乎终于了解了matplotlib中动画是如何工作的基本概念。然而,我仍然不能弄清楚如何使箭头 Flink 在一个地方指向红色圆圈(两个圆圈保持静态,没有动画通过任何手段)。我以为我可以使它工作,只是复制坐标的箭头,从而使帧的数量为2与同一坐标,但不幸的是,它没有工作。我尝试了这里显示的例子:Arrow animation in Python但是ax.clear()并不适合我的需要,而且ax. patchs.remove(patch)由于某种原因无法工作。箭头保持静态并获得“IndexError:列表索引超出范围”错误。我感谢任何建议!
输出:x1c 0d1x
我的代码示例:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib import animation
import matplotlib.patches as patches

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(-20, 20)
ax.set_xlim(-20, 20)

# Drawing static circles:
circle1 = plt.Circle((10, 10), 3, color='red')
circle2 = plt.Circle((-10, -4), 2, color='blue')
ax.add_patch(circle1)
ax.add_patch(circle2)

# Coordinates of the arrow:
x = np.array([2, 2])
y = np.array([2, 2])
dx = x*2
dy = y*2

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

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

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

anim = FuncAnimation(fig, animate, init_func=init,
                     frames=len(x), interval=200)

anim.save('222c.gif', writer='pillow')
plt.show()
plt.close()
weylhg0b

weylhg0b1#

要设置 Flink 的艺术家的动画,最简单的解决方案可能是打开和关闭艺术家的可见性。

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation

import matplotlib.patches as patches

fig, ax = plt.subplots()
ax.set_ylim(-20, 20)
ax.set_xlim(-20, 20)

circle1 = plt.Circle((10, 10), 3, color='red')
circle2 = plt.Circle((-10, -4), 2, color='blue')
ax.add_patch(circle1)
ax.add_patch(circle2)

arrow = patches.Arrow(2, 2, 2, 2)
ax.add_patch(arrow)

def animate(ii):
    if ii % 2:
        arrow.set_visible(False)
    else:
        arrow.set_visible(True)
    return arrow,

anim = FuncAnimation(fig, animate, frames=10, interval=200)
anim.save('test.gif', writer='pillow')
plt.show()

相关问题