【问题标题】:How can I show two animated plots using matplotlib如何使用 matplotlib 显示两个动画图
【发布时间】:2019-08-21 12:35:05
【问题描述】:

我想在 python 中使用 matplotlib 为两个不同的绘图制作动画,但一切都不顺利。

我从一个情节开始,这很好。动画很容易。但现在我想添加第二个动画线图,我很挣扎。我想要第二个情节上的三行。我需要一个带有两个子图的图形吗?还是我需要有两个数字,并有一个子图来代表第二个数字上的三行中的每一行?

我想我需要创建两个动画并引入子情节:

fig, axs = plt.subplots(1,2)
animation1 = FuncAnimation(fig, self.animate_first, numframes, repeat = False, interval = 10, blit = True)
animation2 = FuncAnimation(fig, self.animate_linegraph, numframes, repeat = False, interval = 10, blit = True)

但是如果 subplots 返回单个图形对象,并且这是 FuncAnimation 的第一个参数,那么动画回调函数应该做什么?当我只有一个要显示的图时,我从 animate 函数返回了补丁列表。但是当我有两个情节要更新时。我不知道该怎么办。

非常感谢任何指针。哦(如果不是很明显:)),我对 python 完全陌生。

谢谢, 保罗

【问题讨论】:

  • 这里的“情节”不是很清楚。你想在同一个轴上有两条线被动画吗?还是两个不同轴上的两条线(“子图”)?还是来自不同图形的不同轴上的两条线?
  • @ImportanceOfBeingErnest 我想要两个图形 - 一个显示圆圈移动的动画 - 效果很好。我现在想添加另一个图表以显示在圆形动画旁边。这个新图表我想要在 y 轴上显示 3 条线,在 y 轴上描绘 3 种不同类型的能量,在 x 轴上显示时间。我希望 x 轴也移动 - 所以它可能显示 0 到 10 分钟,但是随着线条的移动,我希望 x 轴也移动,所以可能显示 1 到 11 分钟,2 到 12 分钟, 3 到 13 等。
  • 如果您有 2 个图形,fig1fig2,您可以创建两个 FuncAnimations,每个图形一个。您同样可以创建一个 FuncAnimation 并仍然使用它来更新不同的图形。我不清楚您面临什么问题(这很可能是因为您没有共享产生问题的代码)。

标签: python matplotlib


【解决方案1】:

我过去按照以下思路实现了次情节动画:

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

# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)

# initialization function: plot the background of each frame
def init():
    fig = plt.figure()
    ax2 = fig.add_subplot(2, 1, 1)
    ax3 = fig.add_subplot(2, 1, 2)
    title = plt.title('')
    title.set_text('')
    return fig,ax2,ax3,title

# animation function.  This is called sequentially
def animate(i):

    a = ax2.pcolor(x,y,data)

    b = ax3.pcolor(x2,y2,data2)

    main_title.set_text('Main Title')
    title2.set_text('Sub title 1')
    title3.set_text('Sub title 2')

    return main_title, title2, title3, ax2, ax3

# call the animator.
fig = plt.figure()
ax2 = fig.add_subplot(2, 1, 1)
ax3 = fig.add_subplot(2, 1, 2)
title2 = ax2.set_title('')
title3 = ax3.set_title('')
main_title = fig.suptitle('')


anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=101, interval=250, blit=False)


anim.save('file.mp4', writer=writer)
plt.close()

不确定这是否有帮助,它主要是从我有一段时间没有使用的旧脚本中复制和粘贴...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 2017-11-21
    • 1970-01-01
    • 2018-10-04
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多