Matplotlib的一个步骤动画

4

我正在创建一个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()

它有点类似于我想要的东西(类似下面的gif),但是不同的是,值不是恒定的并随时间滚动,而是每个步骤都是动态的并上下移动。我该如何更改我的代码以实现这种移位?

enter image description here


我有点困惑你想要改变什么。你是说你希望x轴的值增加,这样就更清晰地滚动了吗? - seaotternerd
@seaotternerd 是的,我想这就是我想要的。目前,步骤看起来只是在原地上下移动,没有滚动发生。 - Marmstrong
1个回答

6

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()

注意开头和结尾的部分“步骤”

enter image description here

将此内容融入到您的动画示例中,我们会得到类似于:

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()

enter image description here


有没有办法使步骤均匀分布? - Marmstrong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接