编辑
我将尝试更加精确(由于不需要多余的细节,因此删除了这些细节)
我想制作一个动画,其中一个(红色)球偏离(0,0)并绘制函数sin(x)。该功能必须以蓝色绘制,并且起点必须为红色(如上图所示)
我发现了一种绘制(动画)函数的方法:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'bo')
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True)
plt.show()
我现在的问题是如何使领先点变为红色
有人告诉我应该创建一个空的行元素列表,并使用“ append()”方法添加新的行元素,但是我仍然不知道该怎么做。
引用https://www.physicsforums.com/threads/how-to-make-an-animation-in-sympy-using-python.969906/
谢谢您的帮助。
答案 0 :(得分:2)
肯定有更好的方法:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
points = 50
x = np.linspace(0, 2 * np.pi, points)
y = np.sin(x)
fig, ax = plt.subplots()
ax.set_xlim(-0.3, 2 * np.pi + 0.3)
ax.set_ylim(-1.2, 1.2)
def animate(i):
if i == 0:
# fig.clear()
ax.plot(x[i], y[i], 'ro')
else:
# fig.clear()
ax.plot(x[i-1], y[i-1], 'bo')
ax.plot(x[i], y[i], 'ro')
anim = FuncAnimation(fig, animate, frames=points, repeat=False, interval=150)
plt.show()