python-3.x - 在 Python 中为每个帧中的多个圆圈设置动画
问题描述
我正在尝试使用 Python在此视频中创建动画。但我坚持了第一步。到目前为止,我已经创建了一个圆和一个围绕其圆周旋转的点。我的代码如下。现在我想沿 x 轴绘制y
对应的值 (如代码中的函数所示)。为此,我必须定义另一个函数来绘制这些并将该函数传递到一个新的.x=np.arange(0, I*np.pi, 0.01)
update()
x
y
animation.FuncAnimation()
有没有办法只使用update()
函数来绘制所有内容?
注意我在这里找到了这个动画的代码。但它是用Java编写的!
我的代码
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
W = 6.5
H = 2
radius = 1
I = 2
T = 3
N = 2
plt.style.use(['ggplot', 'dark_background'])
def create_circle(x, y, r):
circle = plt.Circle((x, y), radius=r, fill=False, alpha=0.7, color='w')
return circle
def create_animation():
fig = plt.figure()
ax = plt.axes(xlim=(-2, W + 2), ylim=(-H, H))
circle = create_circle(0, 0, radius)
ax.add_patch(circle)
line1, = ax.plot(0, 1, marker='o', markersize=3, color='pink', alpha=0.7)
def update(theta):
x = radius * np.cos(theta)
y = radius * np.sin(theta)
line1.set_data([0, x], [0, y])
return line1,
anim = []
anim.append(animation.FuncAnimation(fig, update,
frames=np.arange(0, I * np.pi, 0.01),
interval=10, repeat=True))
# anim.append(animation.FuncAnimation(fig, update_line, len(x),
# fargs=[x, y, line, line1], interval=10))
plt.grid(False)
plt.gca().set_aspect('equal')
plt.gca().spines['left'].set_visible(False)
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.gca().spines['bottom'].set_visible(False)
plt.gca().set_xticks([])
plt.gca().set_yticks([])
plt.show()
if __name__ == '__main__':
create_animation()
编辑。我通过定义一个全局变量并以下列方式pos
更改函数来改进任务......动画现在看起来更好但仍然有错误!update()
改进部分
plot, = ax.plot([], [], color='w', alpha=0.7)
level = np.arange(0, I * np.pi, 0.01)
num = []
frames = []
for key, v in enumerate(level):
num.append(key)
frames.append(v)
def update(theta):
global pos
x = radius * np.cos(theta)
y = radius * np.sin(theta)
wave.append(y)
plot.set_data(np.flip(level[:pos] + T), wave[:pos])
line1.set_data([0, x], [0, y])
pos += 1
return line1, plot,
编辑到目前为止,我已经完成了以下操作:
def update(theta):
global pos
x, y = 0, 0
for i in range(N):
prev_x = x
prev_y = y
n = 2 * i + 1
rad = radius * (4 / (n * np.pi))
x += rad * np.cos(n * theta)
y += rad * np.sin(n * theta)
wave.append(y)
circle = create_circle(prev_x, prev_y, rad)
ax.add_patch(circle)
plot.set_data(np.flip(level[:pos] + T), wave[:pos])
line2.set_data([x, T], [y, y])
line1.set_data([prev_x, x], [prev_y, y])
pos += 1
return line1, plot, line2,
请帮助纠正这个动画。或者,有没有什么有效的方法来做这个动画?
编辑好吧,现在动画部分工作。但是有一个小问题:在我的代码中(在 的定义内update()
),我必须添加以每个帧(prev_x, prev_y)
定义的半径为中心的圆。rad
出于这个原因,我尝试for loop
在定义中使用 aupdate()
但所有圆圈都保留在图中(请参见下面的输出)。但我希望在每一帧中都有一个圆,其中心和半径如上所述。同样的问题也出现在plot
. 我尝试在ax.clear()
里面使用,for loop
但它没有用。
解决方案
推荐阅读
- javascript - 在索引范围内的数组中查找项目的最佳方式
- scala - 从本地向 docker kafka Consumer 发送消息
- pentaho - 在 pentaho 中将 STRING 转换为 INT
- java - 如何编写一个从库中调用函数的函数?
- python-3.x - Python在输入一串数字时删除尾随空格
- r - 如何将数据帧从字符转换为数字
- python - 如何从单独的线程获取异步函数结果并停止它
- kotlin - 如何在 Ktor 中完全禁用 CORS?
- python - WEKA 训练和交叉验证
- flutter - 在 null 上调用了 getter 'length' - Flutter