一步的 Matplotlib 动画

Mar*_*ong 4 python animation trigonometry matplotlib

我创建了一个阶跃函数的 Matplotlib 动画。我正在使用以下代码...

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

line, = ax.step([], [])

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 2, 10)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

plt.show()
Run Code Online (Sandbox Code Playgroud)

它模糊地类似于我想要的(类似于下面的 gif),但不是恒定的值和随时间滚动的值,每个步骤都是动态的并且上下移动。如何更改我的代码以实现这种转变?

在此处输入图片说明

Joe*_*ton 5

step明确地绘制输入数据点之间的步骤。它永远无法绘制部分“步骤”。

你想要一个中间有“部分步骤”的动画。

不是ax.step使用ax.plot,而是使用,而是通过绘图来制作一个阶梯式系列y = y - y % step_size

换句话说,类似于:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 1000) # Using a series of 1000 points...
y = np.sin(x)

# Make *y* increment in steps of 0.3
y -= y % 0.3

fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()
Run Code Online (Sandbox Code Playgroud)

注意开头和结尾的部分“步骤” 在此处输入图片说明

将其合并到您的动画示例中,我们将得到类似于以下内容的内容:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

line, = ax.plot([], [])

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    y -= y % 0.3
    line.set_data(x, y)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明