如何使用Matplotlib(Python)在SymPy中制作动画

问题描述 投票:1回答:1

编辑

我会尝试更精确(上面的细节已被删除,因为它们是不必要的):

我想制作一个动画,其中(红色)球离开(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/

谢谢您的帮助。

python matplotlib sympy
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.