【问题标题】:How to animate graph of data in python using matplotlib.animation如何使用 matplotlib.animation 在 python 中为数据图制作动画
【发布时间】:2019-04-01 14:18:40
【问题描述】:

我有两个数组 x 和 y,每个都有超过 365000 个元素。我想使用这些数组元素绘制一条动画线。我正在使用 matplotlib.animation 。问题是当我执行下面的代码时,我看不到平滑(动画)绘制的图形。相反,我看到它是最终绘制的版本。

这是我的代码:

#libs
# Movement instance creation-----------------------------
movement1=Movement(train1, track1)
# # Move the train on the track

movement1.move()
y = movement1.speed
x = movement1.pos

Writer = animation.writers['ffmpeg']
writer = Writer(fps=20, metadata=dict(artist='Me'), bitrate=1800)

fig = plt.figure()
ax = plt.axes(xlim=(0, 25), ylim=(0, 300))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    line.set_data(x, y)
    return line,

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


anim.save('basic_animation.mp4', writer=writer)

这是我期望的类似结果:

当然,我的图表将是另一条曲线。

【问题讨论】:

  • xy 中有什么内容?
  • 它们是数组,例如 x=[0.0004663, 0.0004667, ... 25] y=[0.0002235, 0.0002354, ... 300]
  • 那些是你想要绘制的点?
  • 是的,但以动画方式绘制它们。我的意思是使用这些数组的元素绘制一条动画曲线。我找到了薇薇安的How to Create Animated Graphs in Python。在我更改了这些代码后,我的电脑开始挂起

标签: python matplotlib animation


【解决方案1】:

您的代码基本没问题;你只需要做三件事。

  1. anim_func 的每次迭代中将行的xdataydata 设置为不同的值(否则,就没有动画了,会不会?)

  2. 设置恒定的轴限制,这样您的绘图就不会改变形状

  3. 删除 save 用于显示目的的调用(就我个人而言,我发现它会影响动画)

所以:

ax.axis((x.min(), x.max(), y.min(), y.max())

def animate(i):
    line.set_data(x[:i], y[:i])
    return line,

【讨论】:

  • 如何将此文件 (basic_animation.mp4) 发送到我的 html 模板?
  • @FarkhadL。这可能是一个单独问题的主题。
  • 我已经创建了这个问题,我已经写信给你,因为我在那里没有回复)))stackoverflow.com/questions/55451072/…
  • @FarkhadL。我想帮助你,但是......我对 Flask 了解不多。对不起!
  • 感谢您的关心
【解决方案2】:

您需要定义一组数据,这些数据会发生变化以使动画发生。在您提供的示例站点中,作者通过使用 overdose.iloc[:int(i+1] 对数据进行切片来实现这一点(有关使用的实际代码,请参见下文)。这是在 matplotlib 绘制任何数据时创建动画的部分在 animate 函数中。在您的代码中,您输入 line.set_data(x, y) 我想这是您的整个数据集。这就是它没有移动的原因。

def animate(i):
    data = overdose.iloc[:int(i+1)] #select data range
    p = sns.lineplot(x=data.index, y=data[title], data=data, color="r")
    p.tick_params(labelsize=17)
    plt.setp(p.lines,linewidth=7)

要注意的第二件事是,您的情节在顶部被切断了。这可能是因为您的初始化已经错误地设置了轴。我要做的是添加 plt.axis([0, 25, 0, 'upper limit']) 以帮助正确设置轴。

【讨论】:

  • tps = pd.DataFrame(y,x)Writer = animation.writers['ffmpeg']writer = Writer(fps=20, metadata=dict(artist='Me'), bitrate=1800)def animate(i):data = tps.iloc[:int(30000*i+1)] #select data range p = sns.lineplot(x=data.index, y=data[0], data=data, color="r") p.tick_params(labelsize=17) plt.setp(p.lines,linewidth=7) ani = matplotlib.animation.FuncAnimation(fig, animate, frames=13, repeat=False) ani.save('TPS.mp4', writer=writer)
猜你喜欢
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-28
  • 2020-04-23
  • 1970-01-01
  • 2011-10-09
相关资源
最近更新 更多