I have a problem saving a set of 2D arrays into a Gif. I searched similar titles, but didn't find same problem.
I have 600 files with data, which are 93*226 float arrays. I just need to plot them into a gif file.
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')
So if I set in the loop number of files to read = 50
for i in range(len(files[0:50]))
, it works normally . Or, alternatively if I read all 600 files but save them in small resolution
fig = plt.figure(figsize=(10,7))
...
anim.save('/home/Anton/Heat_1/Heating_1.gif', dpi = 50, writer='imagemagick')
it also works.
However when I set files number larger than ~50 (e.g. 150 as it is shown above) and/or larger figsize, I get an error:
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>
I have removed writer='imagemagick' from
anim.save('/home/Anton/Heat_1/Heating.gif', writer='imagemagick')
and now it works. ¯\_(ツ)_/¯