【问题标题】:Animating Contour Plot in Matplotlib with FuncAnimation [duplicate]使用 FuncAnimation 在 Matplotlib 中动画轮廓图 [重复]
【发布时间】:2019-05-31 16:32:25
【问题描述】:

我正在尝试使用 MatPlotLib FuncAnimation 和等高线图制作一个简单的动画。到目前为止,这是我正在尝试的:

# Create Figure and Axes
figure, ax = plot.subplots()

# Draw new contour with new data from u
def animate(i):
    a = u[:, :, int(i)]
    CS = ax.contourf(x.flatten(), y.flatten(), a, colors=['blue', 'white'], levels=0)
    return CS,

# create animation using the animate() function
myAnimation = FuncAnimation(figure, animate, frames=np.arange(0.0, t, t), interval=10, blit=True)

figure.show()

其中 u[:, :, i] 包含我想在轮廓中绘制的新 Z 数据。

这适用于第一帧,但随后我立即从CS = ax.contourf(...) 行中得到错误:AttributeError: 'QuadContourSet' object has no attribute 'get_zorder' 之后的每次迭代。我确实有一个粗略的动画工作,如下所示:

figure, ax = plot.subplots()
for i in range(0, t):
        a = u[:, :, i]
        CS = ax.contourf(x.flatten(), y.flatten(), a, colors=['blue', 'white'], levels=0)
        figure.show()
        sleep(0.01)

但是这个实现为每个步骤创建了一个新的图表,因此效率不高,这就是我关注 FuncAnimation 的原因。如果有人知道为什么我的 FuncAnimation 不起作用,或者如果有另一种方法可以在一个图表上为我的所有数据设置动画,我将不胜感激!我也尝试使用 clf()、pause() 和 draw() 将其全部绘制在一张图上,但无济于事!

【问题讨论】:

标签: python matplotlib animation contour


【解决方案1】:

另一种选择是使用 ArtistAnimation。您可以使用celluloid(免责声明:我写的)轻松捕捉情节,然后为它们制作动画。它在引擎盖下使用 ArtistAnimation。基本思想是每次您想要动画中的图像时都捕获该图形。然后,当您要求赛璐珞创建动画时,它可以处理其余部分。

请记住,虽然此方法的代码行数可能更少,但运行时间可能会更长,具体取决于动画的长度。与 FuncAnimation 不同,它必须将所有这些情节保存在内存中。

import matplotlib.pyplot as plt
import numpy as np
from celluloid import Camera

X, Y = np.meshgrid(np.linspace(0, 10, 100), np.linspace(0, 10, 100))
fig, ax = plt.subplots()
camera = Camera(fig)
for i in np.linspace(0, 2 * np.pi, 30, endpoint=False):
    ax.contourf(np.sin(X + i) + np.sin(Y - i))
    camera.snap()
anim = camera.animate()
anim.save('contours.mp4')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    相关资源
    最近更新 更多