首页 > 解决方案 > 如何使用 Matplotlib 从头开始​​制作曲线动画

问题描述

请注意,这是如何制作利萨如曲线动画的后续问题;

我的第一个想法是编辑我最初的问题并要求动画,但我理解并尊重 SO 的操作方式。所以最好是提出另一个问题。

我想用参数化制作曲线的动画(你逐渐绘制它):x(t)= sin(3t)和y(y)= sin(4t),其中t [0, 2pi]。

为此,我将添加代码:

from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
ln, = plt.plot([], [], 'b')

def init():
    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    x.append(np.sin(4*frame))
    y.append(np.sin(3*frame))
    ln.set_data(x, y)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)

问题是,使用此代码它不会从头开始绘制整个曲线。什么是透支它,变得重叠。

如何从头开始绘制(即从白色背景开始)?我一直在考虑if else,但一无所获。

谢谢

编辑

让我向您展示整个代码:

%matplotlib notebook

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

# set the minimum potential
rm = math.pow(2, 1 / 6)
t = np.linspace(-10, 10, 1000, endpoint = False)
x = []
y = []

for i in t: #TypeError 'int' object is not iterable
    x_i = np.sin( 3 * i )
    y_i = np.sin( 4 * i )
    x.append(x_i)
    y.append(y_i)

# set the title
plt.title('Plot sin(4t) Vs sin(3t)')

# set the labels of the graph
plt.xlabel('sin(3t)')
plt.ylabel('sin(4t)')

fig, ax = plt.subplots()
ln, = plt.plot([], [], 'b')

def init():
    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    x.append(np.sin(4*frame))
    y.append(np.sin(3*frame))
    ln.set_data(x, y)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)

# display the graph
plt.show()

这是我一开始得到的图像(开始运行后大约 1 秒后截取的屏幕截图;这就是为什么你会看到那条有趣的线):https ://imgur.com/a/bNoViDA 。如您所见,它不是从头开始的(即不是从白色背景开始)

这是我最后得到的情节:https ://imgur.com/a/WQHHUk9

我正在寻求获得那个终点,但从头开始绘制所有内容,而不是从显示的情节开始。

标签: pythonmatplotlibanimation

解决方案


推荐阅读