Ticket #7981: trac-7981-save_ignores_preset_plotting_options.patch

File trac-7981-save_ignores_preset_plotting_options.patch, 8.3 KB (added by novoselt, 12 years ago)

Alternative patch

  • sage/plot/animate.py

    # HG changeset patch
    # User Andrey Novoseltsev <novoselt@gmail.com>
    # Date 1294888483 25200
    # Node ID 80a93e58db038bb24f5ec9f287f11e9f26b3df92
    # Parent  c53a5f2d80eb6138439927f87ec70f91b3fe21f9
    Trac 7981: Make save method aware of the preset plotting options.
    
    diff -r c53a5f2d80eb -r 80a93e58db03 sage/plot/animate.py
    a b  
    8080   
    8181        sage: animate([plot(sin, -1,1)], xmin=0, ymin=0)._Animation__kwds['xmin']
    8282        0
     83       
     84    We check that Trac #7981 is fixed::
     85   
     86        sage: animate([plot(sin(x + float(k), (0, 2*pi), ymin=-5, ymax=5))
     87        ...            for k in srange(0,2*pi,0.3)]).show() # optional
    8388    """
    8489    def __init__(self, v, **kwds):
    8590        r"""
  • sage/plot/plot.py

    diff -r c53a5f2d80eb -r 80a93e58db03 sage/plot/plot.py
    a b  
    315315## imported in functions, so it only gets started if it is actually
    316316## going to be used.
    317317
     318ALLOWED_EXTENSIONS = ['.eps', '.pdf', '.png', '.ps', '.sobj', '.svg']
    318319DEFAULT_FIGSIZE=(6, 3.70820393249937)
    319320DEFAULT_DPI = 100
    320321EMBEDDED_MODE = False
     
    17171718        # This option should not be passed on to save().
    17181719        linkmode = kwds.pop('linkmode', False)
    17191720
    1720         options = {}
    1721         options.update(self.SHOW_OPTIONS)
    1722         options.update(self._extra_kwds)
    1723         options.update(kwds)
    1724 
    17251721        if DOCTEST_MODE:
    1726             options.pop('filename')
    1727             self.save(DOCTEST_MODE_FILE, **options)
     1722            kwds.pop('filename', None)
     1723            self.save(DOCTEST_MODE_FILE, **kwds)
    17281724        elif EMBEDDED_MODE:
    1729             if options['filename'] is None:
    1730                 options['filename'] = sage.misc.misc.graphics_filename()
    1731             self.save(**options)
     1725            kwds.setdefault('filename', sage.misc.misc.graphics_filename())
     1726            self.save(**kwds)
    17321727            if linkmode == True:
    1733                 return "<img src='cell://%s'>" % options['filename']
     1728                return "<img src='cell://%s'>" % kwds['filename']
    17341729            else:
    1735                 html("<img src='cell://%s'>" % options['filename'])
     1730                html("<img src='cell://%s'>" % kwds['filename'])
    17361731        else:
    1737             if options['filename'] is None:
    1738                 options['filename'] = sage.misc.misc.tmp_filename() + '.png'
    1739             self.save(**options)
    1740             os.system('%s %s 2>/dev/null 1>/dev/null &' % \
    1741                 (sage.misc.viewer.browser(), options['filename']))
     1732            kwds.setdefault('filename', sage.misc.misc.tmp_filename() + '.png')
     1733            self.save(**kwds)
     1734            os.system('%s %s 2>/dev/null 1>/dev/null &'
     1735                      % (sage.misc.viewer.browser(), kwds['filename']))
    17421736
    17431737    def xmin(self, xmin=None):
    17441738        """
     
    23462340
    23472341        #subplot.autoscale_view(tight=True)
    23482342        return figure
    2349 
    2350     def save(self, filename=None, dpi=DEFAULT_DPI, savenow=True, *args, **kwds):
     2343       
     2344    # ALLOWED_EXTENSIONS is the list of recognized formats.
     2345    # filename argument is written explicitly so that it can be used as a
     2346    # positional one, which is a very likely usage for this function.
     2347    def save(self, filename=None, **kwds):
    23512348        r"""
    2352         Save the graphics to an image file of type: PNG, PS, EPS, SVG,
    2353         SOBJ, depending on the file extension you give the filename.
    2354         Extension types can be: ``.png``, ``.ps``,
    2355         ``.eps``, ``.svg``, and
    2356         ``.sobj`` (for a Sage object you can load later).
    2357        
     2349        Save the graphics to an image file.
     2350       
     2351        INPUT:
     2352       
     2353        - ``filename`` -- a string (default: autogenerated), the filename and
     2354          the image format given by the extension, which can be one of the
     2355          following:
     2356         
     2357            * ``.eps``,
     2358           
     2359            * ``.pdf``,
     2360           
     2361            * ``.png``,
     2362           
     2363            * ``.ps``,
     2364           
     2365            * ``.sobj`` (for a Sage object you can load later),
     2366           
     2367            * ``.svg``,
     2368           
     2369            * empty extension will be treated as ``.sobj``.
     2370           
     2371        All other keyword arguments will be passed to the plotter.
     2372       
     2373        OUTPUT:
     2374       
     2375        - none.       
    23582376
    23592377        EXAMPLES::
    23602378       
    2361             sage: c = circle((1,1),1,color='red')
    2362             sage: filename=os.path.join(SAGE_TMP, 'test.png')
    2363             sage: c.save(filename, xmin=-1,xmax=3,ymin=-1,ymax=3)
    2364 
    2365         To correct the aspect ratio of certain graphics, you can
    2366         set the ``aspect_ratio`` to 1::
    2367        
    2368             sage: c.save(filename, aspect_ratio=1, xmin=-1, xmax=3, ymin=-1, ymax=3)
    2369 
    2370         You could also just make the dimensions of the picture square
    2371         using ``figsize``::
    2372 
    2373             sage: c.save(filename, figsize=[5,5], xmin=-1, xmax=3, ymin=-1, ymax=3)       
    2374 
    2375         ::
    2376        
    2377             sage: point((-1,1),pointsize=30, color='red')
    2378 
    2379         By default, the figure grows to include all of the graphics
    2380         and text, so the final image may not be exactly the figure
    2381         size you specified.
     2379            sage: c = circle((1,1), 1, color='red')
     2380            sage: filename = os.path.join(SAGE_TMP, 'test.png')
     2381            sage: c.save(filename, xmin=-1, xmax=3, ymin=-1, ymax=3)
     2382
     2383        To correct the aspect ratio of certain graphics, you can set the
     2384        ``aspect_ratio`` to 1::
     2385       
     2386            sage: c.save(filename, aspect_ratio=1,
     2387            ...          xmin=-1, xmax=3, ymin=-1, ymax=3)
     2388
     2389        You could also just make the dimensions of the picture square using
     2390        ``figsize``::
     2391
     2392            sage: c.save(filename, figsize=[5, 5],
     2393            ...          xmin=-1, xmax=3, ymin=-1, ymax=3)       
     2394
     2395        By default, the figure grows to include all of the graphics and text,
     2396        so the final image may not be exactly the figure size you specified.
    23822397        """
     2398        options = dict()
     2399        options.update(self.SHOW_OPTIONS)
     2400        options.update(self._extra_kwds)
     2401        options.update(kwds)
     2402        dpi = options.pop('dpi')
     2403        transparent = options.pop('transparent')
     2404       
     2405        if filename is None:
     2406            filename = options.pop('filename')
    23832407        if filename is None:
    23842408            filename = sage.misc.misc.graphics_filename()
    2385         try:
    2386             ext = os.path.splitext(filename)[1].lower()
    2387         except IndexError:
    2388             raise ValueError, "file extension must be either 'png', 'eps', 'svg' or 'sobj'"
    2389        
    2390         if ext == '' or ext == '.sobj':
     2409        ext = os.path.splitext(filename)[1].lower()
     2410       
     2411        if ext not in ALLOWED_EXTENSIONS:
     2412            raise ValueError("allowed file extensions for images are '"
     2413                             + "', '".join(ALLOWED_EXTENSIONS) + "'!")
     2414        elif ext in ['', '.sobj']:
    23912415            SageObject.save(self, filename)
    2392             return
    2393 
    2394         if savenow:
    2395             options=dict()
    2396             options['transparent']=kwds.pop('transparent',False)
    2397             figure=self.matplotlib(*args, **kwds)
     2416        else:
     2417            figure = self.matplotlib(**options)
    23982418            # You can output in PNG, PS, EPS, PDF, or SVG format, depending on the file extension.
    23992419            # matplotlib looks at the file extension to see what the renderer should be.
    24002420            # The default is FigureCanvasAgg for PNG's because this is by far the most
     
    24022422            # if the file extension is not '.png', then matplotlib will handle it.
    24032423            from matplotlib.backends.backend_agg import FigureCanvasAgg
    24042424            figure.set_canvas(FigureCanvasAgg(figure))
    2405 
    2406             if ext in ['.eps', '.ps', '.pdf']:
    2407                 if dpi is None:
    2408                     dpi = 72
    2409             elif ext == '.svg':
    2410                 if dpi is None:
    2411                     dpi = 80
    2412             elif ext == '.png':
    2413                 if dpi is None:
    2414                     dpi = 100
    2415             else:
    2416                 raise ValueError, "file extension must be either 'png', 'ps, 'eps', 'pdf, 'svg' or 'sobj'"
    2417             figure.savefig(filename,dpi=dpi,bbox_inches='tight',**options)
     2425            figure.savefig(filename, dpi=dpi, bbox_inches='tight',
     2426                           transparent=transparent)
    24182427
    24192428
    24202429_SelectiveFormatterClass = None