def on_savefig ( self ):
        """ Handles the user requesting that the image of the function is to be saved.
        """
        import os
        dlg = FileDialog(parent = self.control, 
                         title = 'Save as image',
                         default_directory=os.getcwd(),
                         default_filename="", wildcard=WILDCARD,
                         action='save as')
        if dlg.open() == OK:
            path = dlg.path

            print "Saving plot to", path, "..."
            try:
                # Now we create a canvas of the appropriate size and ask it to render
                # our component.  (If we wanted to display this plot in a window, we
                # would not need to create the graphics context ourselves; it would be
                # created for us by the window.)
                size=(650,400)
                gc = GraphicsContext(size)
                self.plot_container.draw(gc)
                gc.save(path)
            except:
                print "Error saving!"
                raise
            print "Plot saved."
        return
def draw_plot(filename, size=(800, 600)):

    container = create_plot()
    container.bounds = list(size)
    container.do_layout(force=True)
    gc = GraphicsContext((size[0] + 1, size[1] + 1))
    container.draw(gc)
    gc.save(filename)
    return
Esempio n. 3
0
 def save_plots(self, stem='figure', fmt='pdf'):
     """Saves the current results plots as image file(s)
     
     For Chaco plots: if you want to save as a PDF, then the reportlab 
     library is required since kiva.backend_pdf requires a Canvas object. 
     (Available at http://www.reportlab.org/)
     
     Optional keyword arguments:
     stem -- base filename for image file (default 'figure')
     fmt -- specifies image format for saving, either 'pdf' or 'png'
     """
     if self._no_data():
         return
     
     # Validate format specification
     if fmt not in ('pdf', 'png'):
         self.out("Image format must be either 'pdf' or 'png'", error=True)
         return
     
     # Inline function for creating unique image filenames
     get_filename = \
         lambda stem: unique_path(path.join(self.datadir, stem), 
             fmt="%s_%02d", ext=fmt)
     filename_list = []
     
     # Create and save figure(s) as specified
     figure_saved = False
     if isinstance(self.figure, dict):
         for stem in self.figure:
             f = self.figure[stem]
             if isinstance(stem, str) and isinstance(f, Figure):
                 fn = get_filename(stem)
                 f.savefig(fn)
                 filename_list.append(fn)
         filename_list.sort()
         figure_saved = True
     elif isinstance(self.figure, Figure):
         dpi = self.figure.get_dpi()
         self.figure.set_size_inches(
             (self.figure_size[0]/dpi, self.figure_size[1]/dpi))
         fn = get_filename(stem)
         self.figure.savefig(fn)
         filename_list.append(fn)
         figure_saved = True
     elif isinstance(self.figure, BasePlotContainer):
         container = self.figure
         fn = get_filename(stem)
         container.bounds = list(self.figure_size)
         container.do_layout(force=True)
         if fmt is 'png':
             from enthought.kiva.backend_image import GraphicsContext
             gc = GraphicsContext(
                 (container.bounds[0]+1, container.bounds[1]+1))
             container.draw(gc)
             gc.save(fn)
             figure_saved = True
         elif fmt is 'pdf':
             from enthought.kiva.backend_pdf import GraphicsContext
             try:
                 from reportlab.pdfgen.canvas import Canvas
             except ImportError:
                 self.out('Chaco plot PDF generation requires reportlab!',
                     error=True)
                 return
             gc = GraphicsContext(Canvas(fn))
             container.draw(gc)
             gc.save()
             figure_saved = True
         filename_list.append(fn)
     else:
         self.out('Figure object is not valid. Please recreate.', error=True)
     
     # Output results of save operation and return
     if figure_saved:
         self.out('Figure(s) saved as:\n%s'%('\n'.join(filename_list)))
     else:
         self.out('Plots have not been created!', error=True)            
     return figure_saved