首页 > 解决方案 > 画圆的动画

问题描述

我试图通过画一个简单的圆圈来理解 Matplotlib.animation 的工作原理,但我不明白我做错了什么

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
ax = plt.axes(xlim=(-10,10),ylim=(-10,10))
line, = ax.plot([], [],)
def init():
    line.set_data([], [])
    return line,
def animate(i):
    x = 3*np.sin(np.radians(i))
    y = 3*np.cos(np.radians(i))
    line.set_data(x, y)
    return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,      frames=360, interval=20, blit=True)
plt.show()

它没有画任何东西,我不知道为什么。

标签: pythonmatplotlibanimationgeometrydrawing

解决方案


x 和 y 需要是值数组才能绘制线。

你似乎在你的动画函数中创建了单个浮点数。

如果您试图显示圆逐渐出现,一种方法是在开始时创建一个 X 和 Y 值数组,可能显式地从一个弧度值数组中创建,如下所示:

rads = np.arange(0, 2*np.pi, 0.01)
x = 3*np.sin(rads)
y = 3*np.cos(rads)

然后在 animate 中,您只需将 x 和 y 数组的一部分分配给行数据。

line.set_data(x[0:i], y[0:i])

一整圈的步数将不再是 360,而是 2Pi/0.01。

您可以更改间隔的大小,或更改动画帧的数量来进行调整。


推荐阅读