33from __future__ import division
44
55import os
6+ import sys
7+ import shutil
8+
69import subprocess
710import matplotlib
811
12+ from contextlib import contextmanager
13+
914import matplotlib .pyplot as plt
1015
1116from matplotlib .patches import Circle
@@ -260,7 +265,41 @@ def save(self, filepath, **kwargs):
260265 self .axes .autoscale ()
261266 plt .savefig (filepath , ** kwargs )
262267
263- def saveas_gif (self , filepath , images , delay = 10 , loop = 0 ):
268+ @contextmanager
269+ def gifified (self , func , tempfolder , outfile , pattern = 'image_{}.png' ):
270+ """"""
271+ images = []
272+
273+ def gifify (f ):
274+ def wrapper (* args , ** kwargs ):
275+ f (* args , ** kwargs )
276+ image = os .path .join (tempfolder , pattern .format (len (images )))
277+ images .append (image )
278+ self .save (image )
279+ return wrapper
280+
281+ if not os .path .exists (tempfolder ) or not os .path .isdir (tempfolder ):
282+ os .makedirs (tempfolder )
283+
284+ for file in os .listdir (tempfolder ):
285+ filepath = os .path .join (tempfolder , file )
286+ try :
287+ if os .path .isfile (filepath ):
288+ os .remove (filepath )
289+ except Exception as e :
290+ print (e )
291+
292+ image = os .path .join (tempfolder , pattern .format (len (images )))
293+ images .append (image )
294+ self .save (image )
295+ #
296+ yield gifify (func )
297+ #
298+ self .save_gif (outfile , images )
299+ shutil .rmtree (tempfolder )
300+ print ('done gififying!' )
301+
302+ def save_gif (self , filepath , images , delay = 10 , loop = 0 ):
264303 """Save a series of images as an animated gif.
265304
266305 Parameters
@@ -280,23 +319,9 @@ def saveas_gif(self, filepath, images, delay=10, loop=0):
280319 *convert* being on your system path.
281320
282321 """
283- command = ['convert' , '-delay' , '{}' .format (delay ), '-loop' , '{}' .format (loop )]
322+ command = ['convert' , '-delay' , '{}' .format (delay ), '-loop' , '{}' .format (loop ), '-layers' , 'optimize' ]
284323 subprocess .call (command + images + [filepath ])
285324
286- # def init_animated_gif(self, folder):
287- # if os.path.exists(folder) and os.path.isdir(folder):
288- # if not os.access(folder, os.W_OK):
289- # raise Exception('You do not have write access to this folder: {}'.format(folder))
290- # else:
291- # os.makedirs(folder)
292-
293- # # def save_animated_gif_frame(self):
294- # # pass
295-
296- # def save_animated_gif(self, filepath, images, delay=10, loop=0):
297- # command = ['convert', '-delay', '{}'.format(delay), '-loop', '{}'.format(loop)]
298- # subprocess.call(command + images + [filepath])
299-
300325 def update (self , pause = 0.0001 ):
301326 """Updates and pauses the plot.
302327
0 commit comments