Matplotlib动画的一步

马姆斯特朗

我创建了一个Stepp函数的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),但是值不是恒定的并且随着时间滚动每个步骤都是动态的并且上下移动。如何更改我的代码以实现这一转变?

在此处输入图片说明

乔·金顿

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

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

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

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

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章