使用matplotlib.animation.ArtistAnimation()的.save()方法保存.gif文件时出现IndexError错误

3
我使用plt.plot_surface()plt.scatter() 创建了一系列的3D图片,如下图所示:enter image description here 我想将它们保存为 .gif 格式。根据这个例子,我成功地通过循环查看不同角度并收集图片。
v_angles = [item for item in range(184,264,2)] + [item for item in range(264,183,-2)]

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import PillowWriter

ims = []
for angle in v_angles:
    fig = plt.figure(figsize = (13,8))
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(X, Y, Z, 
                    cmap=plt.cm.coolwarm, 
                    alpha=0.67, 
                    edgecolor='white', 
                    linewidth=0.25, 
                    zorder=-1)
    im = plt.gcf()
    ims.append([im])

将它们保存为matplotlib.animation.ArtistAnimation()对象:

ani = animation.ArtistAnimation(fig, 
                                ims,
                                interval=50,
                                blit=True,
                                repeat_delay=500)

看起来这些图片(ims)确实被收集并且ani正确保存了:

In[574]: ims
Out[575]: 
[[<Figure size 936x576 with 1 Axes>],
 [<Figure size 936x576 with 1 Axes>],
 [<Figure size 936x576 with 1 Axes>],
...

In[576]: ani
Out[577]: <matplotlib.animation.ArtistAnimation at 0x107571fa90>

然而当我尝试创建 .gif 文件时

writer = PillowWriter(fps=20)
ani.save("3d_scatter.gif", writer='imagemagick')


我收到如下的"IndexError"错误:
  File ".../anaconda3/lib/python3.7/site-packages/matplotlib/animation.py", line 575, in finish
    self._frames[0].save(

IndexError: list index out of range

看起来self._frames应该包含项目,但实际上没有。

有人知道如何解决吗?谢谢。

1个回答

0

你在代码的第一部分中犯了一个小错误。应该像这样:

for angle in v_angles:
    fig = plt.figure(figsize = (13,8))
    ax = fig.add_subplot(111, projection='3d')
    im = ax.plot_surface(X, Y, Z,  #        <== NOTE THE CHANGE, I PREFIXED 'im = '.
                    cmap=plt.cm.coolwarm, 
                    alpha=0.67, 
                    edgecolor='white', 
                    linewidth=0.25, 
                    zorder=-1)
    # im = plt.gcf()                        <== THIS LINE CAN BE REMOVED.
    ims.append([im])

您的帖子已经快一年了,但我希望它仍然能对您或其他人有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接