在Gif中保存Matplotlib动画时出错

时间:2018-07-24 08:37:07

标签: python matplotlib gif animated-gif

将一组2D数组保存到Gif中时出现问题。我搜索了相似的标题,但没有发现相同的问题。

我有600个数据文件,它们是93 * 226浮点数组。我只需要将它们绘制到gif文件中即可。

import numpy as np
import os
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib
from  matplotlib.animation import FuncAnimation

# reading files
path = '/home/Anton/Heat'
files = os.listdir(path)
files.sort()
print('Number of files:', len(files))
arr = []

for i in range(len(files[0:150])):  # read files
    file = files[i]
    df = pd.read_csv(path + '/'+ file, sep = ' ', skiprows = 2, header = None) # skip 2 lines
    arr.append(df.values[:,1:]) # skip 1st col
arr = np.array(arr)

fig = plt.figure(figsize=(14,25))
zmin, zmax = 50, 1150  # scale for Z values
norm = matplotlib.colors.Normalize(vmin=zmin, vmax=zmax, clip=False)
im = plt.imshow(np.transpose(arr[0,:,:]), animated = True, cmap = plt.cm.gist_heat, norm=norm)
plt.grid(False)
nst = arr.shape[0] # number of frames in Gif == number of files read

def update(i):
    im.set_array(np.transpose(arr[i,:,:]))
    return im

# create and save animation
anim = FuncAnimation(fig, update, frames=range(nst), interval=50, repeat = False)
anim.save('/home/Anton/Heat_1/Heating_1.gif', writer='imagemagick')

所以如果我在循环中设置要读取的文件数= 50

for i in range(len(files[0:50]))

,它正常工作。或者,或者,如果我读取了所有600个文件,但将它们保存为小分辨率

fig = plt.figure(figsize=(10,7))
...
anim.save('/home/Anton/Heat_1/Heating_1.gif', dpi = 50, writer='imagemagick')

它也可以工作。

但是,当我设置的文件数大于约50(例如上图所示的150)和/或更大的figsize时,会出现错误:

ValueError                                Traceback (most recent call last)
<ipython-input-171-7897cf1b47b2> in <module>()
     91 anim = FuncAnimation(fig, update, interval=50, repeat = False)
---> 92 anim.save('/home/zizin/Heat_1/Heating_1.gif', writer='imagemagick')

~/anaconda3/lib/python3.6/site-packages/matplotlib/animation.py in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs)
   1258                         # TODO: See if turning off blit is really necessary
   1259                         anim._draw_next_frame(d, blit=False)
-> 1260                     writer.grab_frame(**savefig_kwargs)
~/anaconda3/lib/python3.6/contextlib.py in __exit__(self, type, value, traceback)
     97                 value = type()
     98             try:
---> 99                 self.gen.throw(type, value, traceback)
~/anaconda3/lib/python3.6/site-packages/matplotlib/animation.py in saving(self, fig, outfile, dpi, *args, **kwargs)
    235             yield self
    236         finally:
--> 237             self.finish()
~/anaconda3/lib/python3.6/site-packages/matplotlib/animation.py in finish(self)
    367     def finish(self):
    368         '''Finish any processing for writing the movie.'''
--> 369         self.cleanup()
~/anaconda3/lib/python3.6/site-packages/matplotlib/animation.py in cleanup(self)
    406     def cleanup(self):
    407         '''Clean-up and collect the process used to write the movie file.'''
--> 408         out, err = self._proc.communicate()
~/anaconda3/lib/python3.6/subprocess.py in communicate(self, input, timeout)
    841 
    842             try:
--> 843                 stdout, stderr = self._communicate(input, endtime, timeout)
~/anaconda3/lib/python3.6/subprocess.py in _communicate(self, input, endtime, orig_timeout)
   1503                     selector.register(self.stdin, selectors.EVENT_WRITE)
   1504                 if self.stdout:
-> 1505                     selector.register(self.stdout, selectors.EVENT_READ)
~/anaconda3/lib/python3.6/selectors.py in register(self, fileobj, events, data)
    349 
    350         def register(self, fileobj, events, data=None):
--> 351             key = super().register(fileobj, events, data)
~/anaconda3/lib/python3.6/selectors.py in register(self, fileobj, events, data)
    235             raise ValueError("Invalid events: {!r}".format(events))
    236 
--> 237         key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)
~/anaconda3/lib/python3.6/selectors.py in _fileobj_lookup(self, fileobj)
    222         """
    223         try:
--> 224             return _fileobj_to_fd(fileobj)
~/anaconda3/lib/python3.6/selectors.py in _fileobj_to_fd(fileobj)
     37         except (AttributeError, TypeError, ValueError):
     38             raise ValueError("Invalid file object: "
---> 39                              "{!r}".format(fileobj)) from None
ValueError: Invalid file object: <_io.BufferedReader name=54>

1 个答案:

答案 0 :(得分:0)

我已删除writer ='imagemagick' 来自

anim.save('/home/Anton/Heat_1/Heating.gif', writer='imagemagick')

,现在可以使用了。 ¯\ _(ツ)_ /¯