Python pylab.gcf() Examples

The following are 30 code examples of pylab.gcf(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pylab , or try the search function .
Example #1
Source File: image_ocr.py    From pCVR with Apache License 2.0 6 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close() 
Example #2
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close() 
Example #3
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close() 
Example #4
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close() 
Example #5
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close() 
Example #6
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close() 
Example #7
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close() 
Example #8
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close() 
Example #9
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def get_figure_window_geometry(fig='gcf'):
    """
    This will currently only work for Qt4Agg and WXAgg backends.
    Returns position, size

    postion = [x, y]
    size    = [width, height]

    fig can be 'gcf', a number, or a figure object.
    """

    if type(fig)==str:          fig = _pylab.gcf()
    elif _fun.is_a_number(fig): fig = _pylab.figure(fig)

    # Qt4Agg backend. Probably would work for other Qt stuff
    if _pylab.get_backend().find('Qt') >= 0:
        size = fig.canvas.window().size()
        pos  = fig.canvas.window().pos()
        return [[pos.x(),pos.y()], [size.width(),size.height()]]

    else:
        print("get_figure_window_geometry() only implemented for QtAgg backend.")
        return None 
Example #10
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 6 votes vote down vote up
def copy_figure_to_clipboard(figure='gcf'):
    """
    Copies the specified figure to the system clipboard. Specifying 'gcf'
    will use the current figure.
    """    
    try:
        import pyqtgraph as _p
    
        # Get the current figure if necessary        
        if figure is 'gcf': figure = _s.pylab.gcf() 
        
        # Store the figure as an image
        path = _os.path.join(_s.settings.path_home, "clipboard.png")
        figure.savefig(path)
        
        # Set the clipboard. I know, it's weird to use pyqtgraph, but 
        # This covers both Qt4 and Qt5 with their Qt4 wrapper!
        _p.QtGui.QApplication.instance().clipboard().setImage(_p.QtGui.QImage(path))
        
    except:         
        print("This function currently requires pyqtgraph to be installed.") 
Example #11
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def set_figure_window_geometry(fig='gcf', position=None, size=None):
    """
    This will currently only work for Qt4Agg and WXAgg backends.

    postion = [x, y]
    size    = [width, height]

    fig can be 'gcf', a number, or a figure object.
    """

    if type(fig)==str:          fig = _pylab.gcf()
    elif _fun.is_a_number(fig): fig = _pylab.figure(fig)

    # Qt4Agg backend. Probably would work for other Qt stuff
    if _pylab.get_backend().find('Qt') >= 0:
        w = fig.canvas.window()

        if not size == None:
            w.resize(size[0],size[1])

        if not position == None:
            w.move(position[0], position[1])

    # WXAgg backend. Probably would work for other Qt stuff.
    elif _pylab.get_backend().find('WX') >= 0:
        w = fig.canvas.Parent

        if not size == None:
            w.SetSize(size)

        if not position == None:
            w.SetPosition(position) 
Example #12
Source File: plot.py    From TOPFARM with GNU Affero General Public License v3.0 5 votes vote down vote up
def save_plot(self, filename):
        plt.ion()
        targarr = np.array(self.targvalue)
        self.posi[0].set_xdata(self.wt_positions[:,0])
        self.posi[0].set_ydata(self.wt_positions[:,1])
        while len(self.plotel)>0:
            self.plotel.pop(0).remove()
        self.plotel = self.shape_plot.plot(np.array([self.wt_positions[[i,j],0] for i, j in self.elnet_layout.keys()]).T,
                                   np.array([self.wt_positions[[i,j],1]  for i, j in self.elnet_layout.keys()]).T, 'y-', linewidth=1)
        for i in range(len(self.posb)):
            self.posb[i][0].set_xdata(self.iterations)
            self.posb[i][0].set_ydata(targarr[:,i])
            self.legend.texts[i].set_text('%s = %8.2f'%(self.targname[i], targarr[-1,i]))
        self.objf_plot.set_xlim([0, self.iterations[-1]])
        self.objf_plot.set_ylim([0.5, 1.2])
        if not self.title == '':
            plt.title('%s = %8.2f'%(self.title, getattr(self, self.title)))
        plt.draw()
        #print self.iterations[-1] , ': ' + ', '.join(['%s=%6.2f'%(self.targname[i], targarr[-1,i]) for i in range(len(self.targname))])
        with open(self.result_file+'.results','a') as f:
            f.write( '%d:'%(self.inc) + ', '.join(['%s=%6.2f'%(self.targname[i], targarr[-1,i]) for i in range(len(self.targname))]) +
                '\n')
        #plt.show()
        #plt.savefig(filename)
        display(plt.gcf())
        #plt.show()
        clear_output(wait=True) 
Example #13
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def coarsen_all_traces(level=2, exponential=False, axes="all", figure=None):
    """
    This function does nearest-neighbor coarsening of the data. See 
    spinmob.fun.coarsen_data for more information.
    
    Parameters
    ----------
    level=2
        How strongly to coarsen.
    exponential=False
        If True, use the exponential method (great for log-x plots).
    axes="all"
        Which axes to coarsen.
    figure=None
        Which figure to use.
    
    """
    if axes=="gca": axes=_pylab.gca()
    if axes=="all":
        if not figure: f = _pylab.gcf()
        axes = f.axes

    if not _fun.is_iterable(axes): axes = [axes]

    for a in axes:
        # get the lines from the plot
        lines = a.get_lines()

        # loop over the lines and trim the data
        for line in lines:
            if isinstance(line, _mpl.lines.Line2D):
                coarsen_line(line, level, exponential, draw=False)
    _pylab.draw() 
Example #14
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def export_figure(dpi=200, figure="gcf", path=None):
    """
    Saves the actual postscript data for the figure.
    """
    if figure=="gcf": figure = _pylab.gcf()

    if path==None: path = _s.dialogs.Save("*.*", default_directory="save_plot_default_directory")

    if path=="":
        print("aborted.")
        return

    figure.savefig(path, dpi=dpi) 
Example #15
Source File: complete_faces.py    From fancyimpute with Apache License 2.0 5 votes vote down vote up
def save_images(self, images, base_filename, flattened=True):
        self.ensure_dir(self.dirname)
        for i in self.saved_image_indices:
            label = self.labels[i].lower().replace(" ", "_")
            image = images[i, :].copy()
            if flattened:
                image = image.reshape(self.image_shape)
            image[np.isnan(image)] = 0
            figure = pylab.gcf()
            axes = pylab.gca()
            extra_kwargs = {}
            if self.color:
                extra_kwargs["cmap"] = "gray"
            assert image.min() >= 0, "Image can't contain negative numbers"
            if image.max() <= 1:
                image *= 256
            image[image > 255] = 255
            axes.imshow(image.astype("uint8"), **extra_kwargs)
            axes.get_xaxis().set_visible(False)
            axes.get_yaxis().set_visible(False)
            filename = base_filename + ".png"
            subdir = join(self.dirname, label)
            self.ensure_dir(subdir)
            path = join(subdir, filename)
            figure.savefig(
                path,
                bbox_inches='tight')
            self.saved_images[i][base_filename] = path 
Example #16
Source File: execute_example.py    From Assimulo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def savefig(filename = name):
    fig = P.gcf()
    fig.set_size_inches(*(1.0*fig.get_size_inches()))
    fig.set_facecolor([0.69,0.76,0.77])
    fig.text(0.05,0.03,reference_text,size='small')
    return fig.savefig(filename, facecolor=fig.get_facecolor()) 
Example #17
Source File: img.py    From multisensory with Apache License 2.0 5 votes vote down vote up
def from_fig(fig = None, size_inches = None):
  """
  @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
  @param fig a matplotlib figure
  @return a numpy 3D array of RGBA values
  http://www.icare.univ-lille1.fr/wiki/index.php/How_to_convert_a_matplotlib_figure_to_a_numpy_array_or_a_PIL_image  
  """
  if fig is None:
    fig = pylab.gcf()
  if size_inches is not None:
    fig.set_size_inches(*size_inches)
  # draw the renderer
  fig.canvas.draw()
  
  # Get the RGBA buffer from the figure
  w,h = fig.canvas.get_width_height()
  buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8)
  buf.shape = (h, w, 4)
  
  # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
  buf = np.roll(buf, 3, axis = 2)

  # not sure how to set the background to white
  p =  buf[:, :, 3] / 255.
  buf = np.array(buf[:, :, :3] * p[:, :, np.newaxis] + (1 - p)[:, :, np.newaxis]*255, 'uint8')
  return buf 
Example #18
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def get_figure_window(figure='gcf'):
    """
    This will search through the windows and return the one containing the figure
    """

    if figure == 'gcf': figure = _pylab.gcf()
    return figure.canvas.GetParent() 
Example #19
Source File: _spline.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def plot(self, derivative=0, xmin="auto", xmax="auto", steps=500, smooth=0, simple='auto', clear=True, yaxis='left'):
        if simple=='auto': simple = self.simple

        # get the min and max
        if xmin=="auto": xmin = self.xmin
        if xmax=="auto": xmax = self.xmax

        # get and clear the figure and axes
        f = _pylab.gcf()
        if clear and yaxis=='left': f.clf()

        # setup the right-hand axis
        if yaxis=='right':  a = _pylab.twinx()
        else:               a = _pylab.gca()

        # define a new simple function to plot, then plot it
        def f(x): return self.evaluate(x, derivative, smooth, simple)
        _pylab_help.plot_function(f, xmin, xmax, steps, clear, axes=a)

        # label it
        th = "th"
        if derivative == 1: th = "st"
        if derivative == 2: th = "nd"
        if derivative == 3: th = "rd"
        if derivative: self.ylabel = str(derivative)+th+" derivative of "+self.ylabel+" spline"
        a.set_xlabel(self.xlabel)
        a.set_ylabel(self.ylabel)
        a.figure.canvas.Refresh() 
Example #20
Source File: import_labelme.py    From facade-segmentation with MIT License 5 votes vote down vote up
def plot(self):
        """Visualize the label images (e.g. for debugging)

        :return: The current figure
        """
        import pylab
        pylab.imshow(self.image, interpolation='nearest')
        return pylab.gcf() 
Example #21
Source File: megafacade.py    From facade-segmentation with MIT License 5 votes vote down vote up
def save_plots(self, folder):

        import pylab as pl

        pl.gcf().set_size_inches(15, 15)

        pl.clf()
        self.homography.plot_original()
        pl.savefig(join(folder, 'homography-original.jpg'))

        pl.clf()
        self.homography.plot_rectified()
        pl.savefig(join(folder, 'homography-rectified.jpg'))

        pl.clf()
        self.driving_layers.plot(overlay_alpha=0.7)
        pl.savefig(join(folder, 'segnet-driving.jpg'))

        pl.clf()
        self.facade_layers.plot(overlay_alpha=0.7)
        pl.savefig(join(folder, 'segnet-i12-facade.jpg'))

        pl.clf()
        self.plot_grids()
        pl.savefig(join(folder, 'grid.jpg'))

        pl.clf()
        self.plot_regions()
        pl.savefig(join(folder, 'regions.jpg'))

        pl.clf()
        pl.gcf().set_size_inches(6, 4)
        self.plot_facade_cuts()
        pl.savefig(join(folder, 'facade-cuts.jpg'), dpi=300)
        pl.savefig(join(folder, 'facade-cuts.svg'))

        imsave(join(folder, 'walls.png'), self.wall_colors) 
Example #22
Source File: timetrace_scroll_demo3.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def test_plot():
    dx = 1e-3 # this is the sampling period (or grid spacing) of `sample`
    sample = np.random.randn(N_SAMPLES)
    line, = plt.plot([], [], label="Gaussian noise")
    plt.legend(fancybox=True)
    plt.title("Use the slider to scroll and the spin-box to set the width")
    q = ScrollingPlotQT(fig=plt.gcf(), line=line, ydata=sample, dx=1e-3)
    return q   # WARNING: it's important to return this object otherwise
               # python will delete the reference and the GUI will not respond! 
Example #23
Source File: timetrace_scroll_demo2.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def test_plot():
    time = np.arange(N_SAMPLES)*1e-3
    sample = np.random.randn(N_SAMPLES)
    plt.plot(time, sample, label="Gaussian noise")
    plt.title("1000s Timetrace \n (use the slider to scroll and the spin-box "
              "to set the width)")
    plt.xlabel('Time (s)')
    plt.legend(fancybox=True)
    q = ScrollingToolQT(plt.gcf(), scroll_step=1)
    return q   # WARNING: it's important to return this object otherwise
               # python will delete the reference and the GUI will not respond! 
Example #24
Source File: timetrace_scroll_demo.py    From FRETBursts with GNU General Public License v2.0 5 votes vote down vote up
def test_plot():
    time = np.arange(N_SAMPLES)*1e-3
    sample = np.random.randn(N_SAMPLES)
    plt.plot(time, sample, label="Gaussian noise")
    plt.title("1000s Timetrace \n (use the slider to scroll and the spin-box "
              "to set the width)")
    plt.xlabel('Time (s)')
    plt.legend(fancybox=True)
    q = ScrollingToolQT(plt.gcf(), scroll_step=1)
    return q   # WARNING: it's important to return this object otherwise
               # python will delete the reference and the GUI will not respond! 
Example #25
Source File: piecharts.py    From binaryanalysis with Apache License 2.0 5 votes vote down vote up
def generateImages(picklefile, pickledir, filehash, imagedir, pietype):

	leaf_file = open(os.path.join(pickledir, picklefile), 'rb')
	(piedata, pielabels) = cPickle.load(leaf_file)
	leaf_file.close()

	pylab.figure(1, figsize=(6.5,6.5))
	ax = pylab.axes([0.2, 0.15, 0.6, 0.6])

	pylab.pie(piedata, labels=pielabels)

	pylab.savefig(os.path.join(imagedir, '%s-%s.png' % (filehash, pietype)))
	pylab.gcf().clear()
	os.unlink(os.path.join(pickledir, picklefile)) 
Example #26
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 4 votes vote down vote up
def instaprint(figure='gcf', arguments='', threaded=False, file_format='pdf'):
    """
    Quick function that saves the specified figure as a postscript and then
    calls the command defined by spinmob.prefs['instaprint'] with this
    postscript file as the argument.

    figure='gcf'    can be 'all', a number, or a list of numbers
    """

    global _settings

    if 'instaprint' not in _settings.keys():
        print("No print command setup. Set the user variable settings['instaprint'].")
        return

    if   figure=='gcf': figure=[_pylab.gcf().number]
    elif figure=='all': figure=_pylab.get_fignums()
    if not getattr(figure,'__iter__',False): figure = [figure]

    print("figure numbers in queue:", figure)

    figures=[]
    for n in figure: figures.append(_pylab.figure(n))

    # now run the ps printing command
    if threaded:
        # store the canvas type of the last figure
        canvas_type = type(figures[-1].canvas)

        # launch the aforementioned function as a separate thread
        _thread.start_new_thread(_print_figures, (figures,arguments,file_format,))

        # wait until the thread is running
        _time.sleep(0.25)

        # wait until the canvas type has returned to normal
        t0 = _time.time()
        while not canvas_type == type(figures[-1].canvas) and _time.time()-t0 < 5.0:
            _time.sleep(0.1)
        if _time.time()-t0 >= 5.0:
            print("WARNING: Timed out waiting for canvas to return to original state!")

        # bring back the figure and command line
        _pylab.draw()

    else:
        _print_figures(figures, arguments, file_format)
        _pylab.draw() 
Example #27
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 4 votes vote down vote up
def make_inset(figure="current", width=1, height=1):
    """

    This guy makes the figure thick and small, like an inset.
    Currently assumes there is only one set of axes in the window!

    """

    # get the current figure if we're not supplied with one
    if figure == "current": figure = _pylab.gcf()

    # get the window
    w = figure.canvas.GetParent()

    # first set the size of the window
    w.SetSize([220,300])

    # we want thick axis lines
    figure.axes[0].get_frame().set_linewidth(3.0)

    # get the tick lines in one big list
    xticklines = figure.axes[0].get_xticklines()
    yticklines = figure.axes[0].get_yticklines()

    # set their marker edge width
    _pylab.setp(xticklines+yticklines, mew=2.0)

    # set what kind of tickline they are (outside axes)
    for l in xticklines: l.set_marker(_mpl.lines.TICKDOWN)
    for l in yticklines: l.set_marker(_mpl.lines.TICKLEFT)

    # get rid of the top and right ticks
    figure.axes[0].xaxis.tick_bottom()
    figure.axes[0].yaxis.tick_left()

    # we want bold fonts
    _pylab.xticks(fontsize=20, fontweight='bold', fontname='Arial')
    _pylab.yticks(fontsize=20, fontweight='bold', fontname='Arial')

    # we want to give the labels some breathing room (1% of the data range)
    figure.axes[0].xaxis.set_ticklabels([])
    figure.axes[0].yaxis.set_ticklabels([])


    # set the position/size of the axis in the window
    figure.axes[0].set_position([0.1,0.1,0.1+0.7*width,0.1+0.7*height])

    # set the axis labels to empty (so we can add them with a drawing program)
    figure.axes[0].set_title('')
    figure.axes[0].set_xlabel('')
    figure.axes[0].set_ylabel('')

    # set the position of the legend far away
    figure.axes[0].legend=None

    # zoom!
    auto_zoom(figure.axes[0], 0.07, 0.07) 
Example #28
Source File: _spline.py    From spinmob with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, xdata, ydata, smoothing=5000, degree=5, presmoothing=0, plot=True, xlabel="x", ylabel="y", show_derivative=0, xmin="same", xmax="same", simple=0):
        """
        Create a spline object and fit xdata vs ydata with spline
        Set type="interpolate" to simply interpolate the raw data
        """

        # store this stuff for later use
        self.xlabel = xlabel
        self.ylabel = ylabel
        self.xdata  = xdata
        self.ydata  = ydata
        self.simple = simple
        self.xmin = min(xdata)
        self.xmax = max(xdata)
        self._path = "(spline not saved)"
        self.smoothing    = smoothing
        self.degree       = degree
        self.presmoothing = presmoothing
        self.plot_flag    = plot
        self.message = ""
                
        
        # if we're not in simple mode, we have to do a spline fit, not just store the data
        if not simple:        
            # self.ydata might be smoothed
            self.ydata_smoothed = list(ydata)

            # if we're supposed to, presmooth the data
            if presmoothing: _fun.smooth_array(self.ydata_smoothed, presmoothing)

            print("presmoothing = ", str(presmoothing))
            print("smoothing = ",    str(smoothing))
            print("degree    = ",    str(degree))
        
            # do the fit
            self.pfit = _interpolate.splrep(xdata, self.ydata_smoothed, s=smoothing, k=degree)


        # now plot if we're supposed to
        if plot:
            fig  = _pylab.gcf()
            fig.clear()
            axes = fig.gca()
            axes.plot(xdata,ydata, "xr")
            axes.set_xlabel(xlabel)
            axes.set_ylabel(ylabel)
            if not simple:
                axes.plot(xdata,self.ydata_smoothed,"+g")
                self.plot(steps=len(xdata)*5, clear=False)
                _pylab_help.set_all_line_attributes("lw", 2)
                if show_derivative: self.plot(steps=len(xdata)*5, clear=False, derivative=show_derivative, yaxis='right')
                _pylab_help.set_all_line_attributes("lw", 1)
                _pylab_help.set_all_line_attributes("color", "r")

            _pylab_help.set_xrange(xmin, xmax)
            fig.canvas.Refresh()
        

        
    # this takes a single value or an array! 
Example #29
Source File: dataplots.py    From pycopia with Apache License 2.0 4 votes vote down vote up
def Plot(filename=None, data=None, timemarks=None,
    events=None, eventfile=None,
    ylim=None, columns=(0, 1),
    autoscale=True):
    """Plot from ipython.

      Args:
        filename (string): name of a data file to plot. This will be loaded
        into a DataSet object.

        data (DataSet): pre-existing dataset to plot. Mutually exclusive
        with filename parameter.

        timemarks (string): a time spec indicating a span of time to slice.

        eventfile (string): name of data file containing event marks.

        events (DataSet): A pre-existing event dataset.

        ylim (tuple of (min, max): minimum and maximum Y values to plot.

        columns (int, or sequence of ints): The column number, or numbers,
        starting from zero that will be extracted out (vertical slice).

        autoscale (bool): If True, automatically fit graph scale to data.
        False means use a fixed scale (2.5 amp max).

    """
    if filename is not None:
        data = dataset.DataSet(filename=filename)
    if eventfile is not None:
        events = dataset.DataSet(filename=eventfile)
    if data is None:
        print "You should supply a filename or a dataset."
        return
    if timemarks:
            data.timeslice(timemarks)

    make_plots(data, ylim=ylim, events=events,
            columns=columns, autoscale=autoscale, interactive=True)
    pylab.gcf().set_size_inches((9,7))
    #plotaxes = pylab.gca()
    pylab.subplots_adjust(bottom=0.15)
    pylab.ion()
    pylab.show() 
Example #30
Source File: dataplots.py    From pycopia with Apache License 2.0 4 votes vote down vote up
def make_plots(dset, timemarks="0s,9d", ylim=None, columns=None,
            autoscale=False, events=None, interactive=False):
    pylab.ioff()
    names = []
    if type(events) is dataset.DataSet:
        events.normalize_time(dset.measurements[0][0])
    dset.normalize_time()
    unit = dset.unit

    for subset, start, end in dset.get_timeslices(timemarks):
        if len(subset) > 0:
            datacols, labels = subset.get_columns(columns)
            x_time = datacols[0]
            if len(x_time) < 100:
                mrk = "."
                ls = "-"
            else:
                mrk = ","
                ls = "None"
            for col, label, color in itertools.izip(datacols[1:], labels[1:], color_cycler):
                pylab.plot(x_time, col, color=color, label=label, ls=ls, marker=mrk)
            pylab.setp(pylab.gcf(), dpi=100, size_inches=(9,6))
            pylab.xlabel("Time (s)")
            pylab.ylabel(unit)

            if events is not None:
                ax = pylab.gca()
                for row in events:
                    ax.axvline(row[0], color="rgbymc"[int(row[1]) % 6])

            metadata = subset.metadata
            title = "%s-%s-%s-%ss-%ss" % (metadata.name,
                    metadata.timestamp.strftime("%m%d%H%M%S"),
                    "-".join(labels),
                    int(start),
                    int(end))
            pylab.title(title, fontsize="x-small")
            font = FontProperties(size="x-small")
            pylab.legend(prop=font)

            if not interactive:
                fname = "%s.%s" % (title, "png")
                pylab.savefig(fname, format="png")
                names.append(fname)
                pylab.cla()
        else:
            break
    return names


# Functions for interactive reporting from command line.