首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用带有matplotlib.animation.ArtistAnimation()的.save()方法保存.gif IndexError

使用带有matplotlib.animation.ArtistAnimation()的.save()方法保存.gif IndexError
EN

Stack Overflow用户
提问于 2020-02-07 05:02:41
回答 1查看 381关注 0票数 2

我已经使用plt.plot_surface()plt.scatter()创建了一系列3D图像,如下所示:

我想把它们保存为.gif。在this example之后,我能够循环浏览视角并收集图像:

代码语言:javascript
复制
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()对象:

代码语言:javascript
复制
ani = animation.ArtistAnimation(fig, 
                                ims,
                                interval=50,
                                blit=True,
                                repeat_delay=500)

看起来图像(ims)确实被收集并正确地保存了ani

代码语言:javascript
复制
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时

代码语言:javascript
复制
writer = PillowWriter(fps=20)
ani.save("3d_scatter.gif", writer='imagemagick')

我得到了以下IndexError

代码语言:javascript
复制
  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应该包含项,但并不包含。

有人知道怎么解决这个问题吗?谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-01-22 17:53:31

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

代码语言:javascript
复制
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])

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60103471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档