【问题标题】:Matplotlib animation of a stepMatplotlib 一步动画
【发布时间】:2015-05-10 18:10:02
【问题描述】:

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

【问题讨论】:

  • 我对您想要更改的内容有点困惑。您是说希望 x 轴值增加,以便更清晰地滚动?
  • @seaotternerd 是的,我认为这就是我想要的。目前,这些步骤看起来就像在原地上下移动,没有发生滚动。

标签: python animation matplotlib trigonometry


【解决方案1】:

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

【讨论】:

  • 有没有办法让台阶均匀分布?
猜你喜欢
  • 2021-10-27
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多