Python matplotlib.pyplot.ioff() Examples

The following are code examples for showing how to use matplotlib.pyplot.ioff(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: DeepQMC   Author: NLESC-JCER   File: plot_potential.py    Apache License 2.0 6 votes vote down vote up
def plot_results_1d(net, domain, res, sol=None, e0=None, load=None):
    ''' Plot the summary of the results for a 1D problem.

    Args:
        net : network object
        obs_dict : dict containing the obserable
        sol : callable of the solutions
        e0 : energy of the solution
        domain : boundary of the plot
        res : number of points in the x axis
    '''
    plt.ioff()
    fig = plt.figure()
    ax0 = fig.add_subplot(211)
    ax1 = fig.add_subplot(212)

    plot_wf_1d(net, domain, res, sol=sol, hist=False, ax=ax0, load=load)
    plot_observable(net.obs_dict, e0=e0, ax=ax1)

    plt.show()


##############################################################################
# 2D routnines
############################################################################## 
Example 2
Project: DeepQMC   Author: NLESC-JCER   File: plot_potential.py    Apache License 2.0 6 votes vote down vote up
def plot_results_2d(net, domain, res, sol=None, e0=None, load=None):
    ''' Plot the summary of the results for a 1D problem.

    Args:
        net : network object
        obs_dict : dict containing the obserable
        sol : callable of the solutions
        e0 : energy of the solution
        domain : boundary of the plot
        res : number of points in the x axis
    '''
    plt.ioff()
    fig = plt.figure()
    ax0 = fig.add_subplot(211, projection='3d')
    ax1 = fig.add_subplot(212)

    plot_wf_2d(net, domain, res, sol=sol, ax=ax0, load=load)
    plot_observable(net.obs_dict, e0=e0, ax=ax1)

    plt.show()

##############################################################################
# 3D routnines
############################################################################## 
Example 3
Project: DeepQMC   Author: NLESC-JCER   File: plot_potential.py    Apache License 2.0 6 votes vote down vote up
def plot_results_3d(net, obs_dict, domain, res, wf=False, isoval=0.02,
                    sol=None, e0=None, hist=False):
    ''' Plot the summary of the results for a 1D problem.

    Args:
        net : network object
        obs_dict : dict containing the obserable
        domain : boundary of the plot
        res : number of points in the x axis
        sol : callable of the solutions
        e0 : energy of the solution
    '''
    plt.ioff()
    fig = plt.figure()
    ax0 = fig.add_subplot(211, projection='3d')
    ax1 = fig.add_subplot(212)

    plot_wf_3d(net, domain, res, wf=wf, sol=sol,
               isoval=isoval, hist=hist, ax=ax0)
    plot_observable(obs_dict, e0=e0, ax=ax1)

    plt.show() 
Example 4
Project: infusion   Author: jiamings   File: infusion.py    MIT License 6 votes vote down vote up
def train(self, alpha=0.05, num_epochs=30):
        self.sess.run(tf.global_variables_initializer())
        batch_size = 64
        plt.ion()
        start_time = time.time()
        for epoch in range(0, num_epochs):
            batch_idxs = 1093
            self.visualize(alpha)
            for idx in range(0, batch_idxs):
                bx, _ = mnist.train.next_batch(batch_size)
                loss, _ = self.sess.run([self.loss, self.trainer], feed_dict={self.x: bx, self.alpha: alpha})
                if idx % 100 == 0:
                    print("Epoch: [%2d] [%4d/%4d] time: %4.4f, " %
                          (epoch, idx, batch_idxs, time.time() - start_time), end='')
                    print("loss: %4.4f" % loss)
        plt.ioff()
        self.visualize(alpha=0.0, batch_size=20) 
Example 5
Project: infusion   Author: jiamings   File: infusion.py    MIT License 6 votes vote down vote up
def train(self, alpha=0.05, num_epochs=30):
        self.sess.run(tf.global_variables_initializer())
        batch_size = 128
        plt.ion()
        start_time = time.time()
        for epoch in range(0, num_epochs):
            batch_idxs = 545
            #self.visualize(alpha)
            for idx in range(0, batch_idxs):
                bx, _ = mnist.train.next_batch(batch_size)
                bz = self.sess.run(self.rand_init, feed_dict={self.x: bx, self.alpha: alpha})
                loss, _ = self.sess.run([self.loss, self.trainer], feed_dict={self.x: bx, self.alpha: alpha, self.init: bz})
                if idx % 100 == 0:
                    print("Epoch: [%2d] [%4d/%4d] time: %4.4f, " %
                          (epoch, idx, batch_idxs, time.time() - start_time), end='')
                    print("loss: %4.4f" % loss)
            self.visualize(alpha=0.0, batch_size=10, repeat=2)
        plt.ioff()
        self.visualize(alpha=0.0, batch_size=20, repeat=2) 
Example 6
Project: hierarchical-sparse-coding   Author: sbrodeur   File: modeling.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _updateResidual(self, residual, energyResidual, atoms, D, eps=1e-16):

        energyLoss = 0.0
        for atom in atoms:
            # Update the residual by removing the contribution of the selected filter
            # NOTE: negate the coefficient to actually perform a overlap-remove operation.
            localEnergyBefore = np.sum(np.square(peek(residual, atom.length, atom.position)))
            overlapAdd(residual, -atom.coefficient*D[atom.index], atom.position, copy=False)
            localEnergyAfter = np.sum(np.square(peek(residual, atom.length, atom.position)))
            energyLoss += (localEnergyBefore - localEnergyAfter)
        
        if energyLoss < 0.0 and np.abs(energyLoss) > eps:
            logger.warn('Residual energy (%f) increased by %4.18f' % (energyResidual, -energyLoss))
            
            if self.verbose:
                plt.ioff()
                plt.show()
            #assert energyLoss >= 0.0
        energyResidual -= energyLoss
        
        return residual, energyResidual 
Example 7
Project: pymaid   Author: schlegelp   File: core.py    GNU General Public License v3.0 6 votes vote down vote up
def _gen_svg_thumbnail(self):
        import matplotlib.pyplot as plt
        # Store some previous states
        prev_level = logger.getEffectiveLevel()
        prev_pbar = config.pbar_hide
        prev_int = plt.isinteractive()

        plt.ioff()  # turn off interactive mode
        logger.setLevel('WARNING')
        config.pbar_hide = True
        fig = plt.figure(figsize=(2, 2))
        ax = fig.add_subplot(111)
        fig, ax = self.plot2d(connectors=False, ax=ax)
        output = io.StringIO()
        fig.savefig(output, format='svg')

        if prev_int:
            plt.ion()  # turn on interactive mode
        logger.setLevel(prev_level)
        config.pbar_hide = prev_pbar
        _ = plt.clf()
        return output.getvalue() 
Example 8
Project: pix2shape   Author: rajeswar18   File: renderer.py    MIT License 6 votes vote down vote up
def render_scene(scene):
    res = render(scene)
    im = res['image']

    import matplotlib.pyplot as plt
    plt.ion()
    plt.figure()
    plt.imshow(im)
    plt.title('Final Rendered Image')
    plt.savefig('img_np.png')

    depth = res['depth']
    plt.figure()
    plt.imshow(depth)
    plt.title('Depth Image')
    plt.savefig('img_depth_np.png')

    plt.ioff()
    plt.show()
    return res 
Example 9
Project: metatlas   Author: biorack   File: metatlas_get_data_helper_fun.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compare_EIC_to_BPC_for_file(metatlas_dataset,file_index,yscale = 'linear'):
    """
    Plot the base peak chromatogram overlaid with extracted
    ion chromatograms for features
    Input
    metatlas_dataset: a list of lists containing all atlas, file, and feature information
    file_index: the integer index of which file to plot
    """
    full_file_names = get_file_names(metatlas_dataset,full_path=True)
    base_file_names = get_file_names(metatlas_dataset,full_path=False)
    bpc = get_bpc(full_file_names[file_index])
    plt.ioff()
    fig = plt.figure()
    plt.plot(bpc.rt,bpc.i,'k-')
    for d in metatlas_dataset[file_index]:
        plt.plot(d['data']['eic']['rt'],d['data']['eic']['intensity'],'r.',alpha=0.2)
    ax = plt.gca()
    ax.set_yscale(yscale)
    ax.set_title('\n'.join(wrap(base_file_names[file_index],50)))
    ax.set_xlabel('Retention Time (min)')
    ax.set_ylabel('Intensity')
    plt.close(fig)
    return fig 
Example 10
Project: metatlas   Author: biorack   File: dill2plots.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_errorbar_plots(df,output_loc=''):

    output_loc = os.path.expandvars(output_loc)
    if not os.path.exists(output_loc):
        os.makedirs(output_loc)

    plt.ioff()
    for compound in df.index:
        m = df.ix[compound].groupby(level='group').mean()
        e = df.ix[compound].groupby(level='group').std()
        c = df.ix[compound].groupby(level='group').count()

        for i in range(len(e)):
            if c[i]>0:
                e[i] = e[i] / c[i]**0.5

        f, ax = plt.subplots(1, 1,figsize=(12,12))
        m.plot(yerr=e, kind='bar',ax=ax)
        ax.set_title(compound,fontsize=12,weight='bold')
        plt.tight_layout()
        f.savefig(os.path.join(output_loc, compound + '_errorbar.pdf'))

        #f.clear()
        plt.close(f)#f.clear() 
Example 11
Project: metatlas   Author: biorack   File: spectralprocessing.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def histogram_edge_frequency(edge_count):
    """
    Input:
    * edge_count: list of dicts generated by metatlas.spectralprocessing.make_edges()

    Output:
    * fig, ax: a figure and axes handles for the frequency of occurnce of various edges in your network

    See Also:
    metatlas.spectralprocessing.make_edges()

    """
    plt.ioff()
    ec_df = pd.DataFrame(edge_count)
    sorted_mass_difference = pd.merge(ec_df,mass_differences,left_on='edge_index',right_index=True).drop(columns=['edge_index']).sort_values('edge_count',ascending=False)
    sorted_mass_difference.reset_index(inplace=True)
    fig,ax = plt.subplots(figsize=(14,7))
    sorted_mass_difference.plot.bar(x='formula',y='edge_count',ax=ax,color='black')
    ax.set_ylabel('edge count')
    plt.ion()
    return fig,ax 
Example 12
Project: osim-rl   Author: stanfordnmbl   File: solver.py    MIT License 6 votes vote down vote up
def plot_convergence(self, filename=None):
        yy = self.iter_values
        xx = range(len(yy))
        import matplotlib.pyplot as plt
        # Plot
        plt.ioff()
        fig = plt.figure()
        fig.set_size_inches(18.5, 10.5)
        font = {'size': 28}
        plt.title('Value over # evaluations')
        plt.xlabel('X', fontdict=font)
        plt.ylabel('Y', fontdict=font)
        plt.plot(xx, yy)
        plt.axes().set_yscale('log')
        if filename is None:
            filename = 'plots/iter.png'
        plt.savefig(filename, bbox_inches='tight')
        plt.close(fig)
        print('plotting convergence OK.. ' + filename) 
Example 13
Project: Nyles   Author: pvthinker   File: animate.py    MIT License 6 votes vote down vote up
def run(self):
        """Create the animation and optionally save it."""
        if not self.video_path:
            plt.ioff()
        self.anim = animation.FuncAnimation(
            self.p.fig,
            self.update,
            frames=self.n_frames,
            repeat=False,
            interval=0,
        )
        if self.visible:
            plt.show()
        if self.video_path:
            self.anim.save(
                self.video_path,
                fps=FPS,
                dpi=DPI,
                bitrate=BPS,
                metadata=self.metadata,
            ) 
Example 14
Project: foucluster   Author: cperales   File: plot.py    MIT License 6 votes vote down vote up
def fourier_plot(freq, features,
                 folder=None,
                 filename=None):
    """
    
    """
    fig = plt.figure(1)
    # Turn interactive plotting off
    plt.ioff()
    plt.plot(freq, features)
    plt.xlabel('frequency')
    plt.ylabel('amplitude')
    if filename is not None:
        f = '' if folder is None else folder
        plt.savefig(os.path.join(f,
                                 filename + '.png'))
    plt.close(fig) 
Example 15
Project: foucluster   Author: cperales   File: plot.py    MIT License 6 votes vote down vote up
def song_plot(aud_data,
              folder=None,
              filename=None):
    fig = plt.figure(1)
    # Turn interactive plotting off
    plt.ioff()
    plt.plot(aud_data)
    plt.xlabel('time')
    plt.ylabel('amplitude')
    plt.xticks([])
    plt.yticks([])
    if filename is not None:
        f = '' if folder is None else folder
        plt.savefig(os.path.join(f,
                                 filename + '.png'))
    plt.close(fig) 
Example 16
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def grid_visual(data):
    """
    This function displays a grid of images to show full misclassification
    :param data: grid data of the form;
        [nb_classes : nb_classes : img_rows : img_cols : nb_channels]
    :return: if necessary, the matplot figure to reuse
    """
    import matplotlib.pyplot as plt

    # Ensure interactive mode is disabled and initialize our graph
    plt.ioff()
    figure = plt.figure()
    figure.canvas.set_window_title('Cleverhans: Grid Visualization')

    # Add the images to the plot
    num_cols = data.shape[0]
    num_rows = data.shape[1]
    num_channels = data.shape[4]
    current_row = 0
    for y in xrange(num_rows):
        for x in xrange(num_cols):
            figure.add_subplot(num_rows, num_cols, (x + 1) + (y * num_cols))
            plt.axis('off')

            if num_channels == 1:
                plt.imshow(data[x, y, :, :, 0], cmap='gray')
            else:
                plt.imshow(data[x, y, :, :, :])

    # Draw the plot and return
    plt.show()
    return figure 
Example 17
Project: GeoPy   Author: aerler   File: old_plots.py    GNU General Public License v3.0 5 votes vote down vote up
def hovmoellerPlot(varlist, clevs=None,cbls=None,title='',subplot=(),slices={},figargs={'figsize':(8,8)},**plotargs):
  import matplotlib.pylab as pyl    
  from pygeode.axis import XAxis, YAxis, TAxis
  from plotting.misc import multiPlot, sharedColorbar
  if not isinstance(varlist,list): varlist = [varlist]
  if not isinstance(clevs,list): clevs = [clevs]
  if not isinstance(cbls,list): cbls = [cbls]
  pyl.ioff() # non-interactive mode
  # construct figure and axes    
  f = pyl.figure(**figargs)    
  f.clf()
  # create zonal-mean variables
  titles = [var.name for var in varlist]
  plotlist = [var(**slices).mean(XAxis).transpose(YAxis,TAxis) for var in varlist] # latitude sliced
  # organize colorbar (cleanup arguments) 
  colorbar = plotargs.pop('colorbar',{})
  manualCbar = colorbar.pop('manual',False)
  if manualCbar: cbar = False
  else: cbar = colorbar 
  # set default margins  
  defaultMargins = {'left':0.065,'right':0.975,'bottom':0.05,'top':0.95,'wspace':0.05,'hspace':0.1}
  defaultMargins.update(plotargs.pop('margins',{}))
  ## make subplots
  (f,cf,subplot) = multiPlot(f=f,varlist=plotlist,titles=titles,clevs=clevs,cbls=cbls,subplot=subplot, #
                     colorbar=cbar,margins=defaultMargins,**plotargs)
  if title: f.suptitle(title,fontsize=14) 
  ## add common colorbar
  if manualCbar:
    f = sharedColorbar(f, cf, clevs, colorbar, cbls, subplot, defaultMargins)        
  # finalize
  pyl.draw(); # pyl.ion();
  return f 
Example 18
Project: Fall-Detection-with-CNN   Author: munnam77   File: temporalnetgeneral.py    MIT License 5 votes vote down vote up
def plot_training_info(case, metrics, save, history):
    # summarize history for accuracy
    plt.ioff()
    if 'accuracy' in metrics:     
        fig = plt.figure()
        plt.plot(history['acc'])
        plt.plot(history['val_acc'])
        plt.title('model accuracy')
        plt.ylabel('accuracy')
        plt.xlabel('epoch')
        plt.legend(['train', 'val'], loc='upper left')
        if save == True:
            plt.savefig(case + 'accuracy.png')
            plt.gcf().clear()
        else:
            plt.show()
        plt.close(fig)

    # summarize history for loss
    if 'loss' in metrics:
        fig = plt.figure()
        plt.plot(history['loss'])
        plt.plot(history['val_loss'])
        plt.title('model loss')
        plt.ylabel('loss')
        plt.xlabel('epoch')
        #plt.ylim(1e-3, 1e-2)
        plt.yscale("log")
        plt.legend(['train', 'val'], loc='upper left')
        if save == True:
            plt.savefig(case + 'loss.png')
            plt.gcf().clear()
        else:
            plt.show()
        plt.close(fig) 
Example 19
Project: pysat   Author: pysat   File: test_ssnl_plot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_scatterplot_w_ioff(self):
        """Check if scatterplot generates"""

        plt.ioff()
        figs = plot.scatterplot(self.testInst, 'longitude', 'latitude',
                                'slt', [0.0, 24.0])

        axes = figs[0].get_axes()
        assert len(figs) == 1
        assert len(axes) == 3
        assert not mpl.is_interactive() 
Example 20
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def _enter_plotting(self, fontsize=9):
        """assumes that a figure is open """
        # interactive_status = matplotlib.is_interactive()
        self.original_fontsize = pyplot.rcParams['font.size']
        pyplot.rcParams['font.size'] = fontsize
        pyplot.hold(False)  # opens a figure window, if non exists
        pyplot.ioff() 
Example 21
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 22
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 23
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools (Deokwoo Jung's conflicted copy 2014-07-01).py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-'):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(diff(data_x.__dict__[key].val))
            title(key+'- Differential',fontsize='small')
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            title(key,fontsize='small')
        
        plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
    
    plt.xticks(fontsize='small')
    plt.yticks(fontsize='small')
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 24
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 25
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 26
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 27
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 28
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 29
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 30
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 31
Project: ehtplot   Author: liamedeiros   File: figure.py    GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, **kwargs):
        """Figure realizer

        The Figure class only keeps track of a root panel.  It does
        not contain an actual matplotlib Figure instance.  Whenever a
        figure needs to be created, Figure creates a new matplotlib
        Figure in order to drew/rendered/realized the figure.

        Args:

            **kwargs (dict): Arbitrary Figure-specific keyworded
                arguments that are used to construct the matplotlib
                Figure.

        """
        kwprops = merge_dict(self.kwprops, kwargs)
        style   = kwprops.pop('style')

        with mpl.rc_context():
            mpl.rcdefaults()
            plt.style.use(style)

            imode = mpl.is_interactive()
            if imode:
                plt.ioff()

            fig = plt.figure(**kwprops)
            ax  = newaxes(fig)
            yield fig, ax

            if imode:
                plt.ion() 
Example 32
Project: pyris   Author: fmonegaglia   File: misc.py    MIT License 5 votes vote down vote up
def _set_mask( self ):
        '''
        Interactively select areas through drag-and-drop
        '''
        real_color = self.build_real_color()
        white_masks = []
        plt.ioff()
        fig = plt.figure()
        plt.title( 'Press-drag a rectangle for your mask. Close when you are finish.' )
        plt.imshow( real_color, cmap='binary_r' )
        plt.axis('equal')
        x_press = None
        y_press = None
        def onpress(event):
            global x_press, y_press
            x_press = int(event.xdata) if (event.xdata != None) else None
            y_press = int(event.ydata) if (event.ydata != None) else None
        def onrelease(event):
            global x_press, y_press
            x_release = int(event.xdata) if (event.xdata != None) else None
            y_release = int(event.ydata) if (event.ydata != None) else None
            if (x_press != None and y_press != None
                and x_release != None and y_release != None):
                (xs, xe) = (x_press, x_release+1) if (x_press <= x_release) \
                  else (x_release, x_press+1)
                (ys, ye) = (y_press, y_release+1) if (y_press <= y_release) \
                  else (y_release, y_press+1)
                print( "The mask you selected is [{0}:{1},{2}:{3}]".format(
                    xs, xe, ys, ye) )
                white_masks.append( [ ys, ye, xs, xe ] )
                plt.fill( [xs,xe,xe,xs,xs], [ys,ys,ye,ye,ys], 'r', alpha=0.25 )
                event.canvas.draw()
            x_press = None
            y_press = None
        cid_press   = fig.canvas.mpl_connect('button_press_event'  , onpress  )
        cid_release = fig.canvas.mpl_connect('button_release_event', onrelease)
        plt.show()
        return white_masks 
Example 33
Project: pyris   Author: fmonegaglia   File: misc.py    MIT License 5 votes vote down vote up
def __call__( self ):
        #real_color = self.build_real_color()
        white_masks = []
        plt.ioff()
        fig = plt.figure()
        plt.title( 'Press-drag a rectangle for your mask. Close when you are finish.' )
        plt.imshow( self.bg, cmap='binary_r' )
        plt.imshow( self.bw, cmap='jet', alpha=0.5 )
        plt.axis('equal')
        x_press = None
        y_press = None
        def onpress(event):
            global x_press, y_press
            x_press = int(event.xdata) if (event.xdata != None) else None
            y_press = int(event.ydata) if (event.ydata != None) else None
        def onrelease(event):
            global x_press, y_press
            x_release = int(event.xdata) if (event.xdata != None) else None
            y_release = int(event.ydata) if (event.ydata != None) else None
            if (x_press != None and y_press != None
                and x_release != None and y_release != None):
                (xs, xe) = (x_press, x_release+1) if (x_press <= x_release) \
                  else (x_release, x_press+1)
                (ys, ye) = (y_press, y_release+1) if (y_press <= y_release) \
                  else (y_release, y_press+1)
                print( "Slice [{0}:{1},{2}:{3}] will be set to {4}".format(
                    xs, xe, ys, ye, 0) )
                self.bw[ ys:ye,xs:xe ] = 0
                plt.fill( [xs,xe,xe,xs,xs], [ys,ys,ye,ye,ys], 'r', alpha=0.25 )
                event.canvas.draw()
            x_press = None
            y_press = None
        cid_press   = fig.canvas.mpl_connect('button_press_event'  , onpress  )
        cid_release = fig.canvas.mpl_connect('button_release_event', onrelease)
        plt.show()
        return self.bw 
Example 34
Project: PyFluxPro   Author: OzFlux   File: pfp_cpd.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_hist(S,mu,sig,crit_t,year,d):
    if len(S)<=1:
        logger.info(" plot_hist: 1 or less values in S for year "+str(year)+", skipping histogram ...")
        return
    S=S.reset_index(drop=True)
    x_low=S.min()-0.1*S.min()
    x_high=S.max()+0.1*S.max()
    x=np.linspace(x_low,x_high,100)
    if d["show_plots"]:
        plt.ion()
    else:
        plt.ioff()
    fig=plt.figure(figsize=(12,8))
    #fig.patch.set_facecolor('white')
    #plt.hist(S,normed=True)
    plt.hist(S, density=True)
    plt.xlim(x_low,x_high)
    plt.xlabel(r'u* ($m\/s^{-1}$)',fontsize=16)
    if np.isfinite(mu) and np.isfinite(sig):
        plt.plot(x,stats.norm.pdf(x,mu,sig),color='red',linewidth=2.5,label='Gaussian PDF')
        plt.axvline(x=mu-sig*crit_t,color='black',linestyle='--')
        plt.axvline(x=mu+sig*crit_t,color='black',linestyle='--')
        plt.axvline(x=mu,color='black',linestyle='dotted')
    txt='mean u*='+str(mu)
    ax=plt.gca()
    props = dict(boxstyle='round,pad=1', facecolor='white', alpha=0.5)
    plt.text(0.4,0.1,txt,bbox=props,fontsize=12,verticalalignment='top',transform=ax.transAxes)
    plt.legend(loc='upper left')
    plt.title(str(year)+'\n')
    plot_out_name=os.path.join(d["plot_path"],d["site_name"]+'_CPD_'+str(year)+'.png')
    fig.savefig(plot_out_name)
    if d["show_plots"]:
        plt.draw()
        plt.ioff()
    else:
        plt.ion()
    #if d["call_mode"].lower()!="interactive": plt.close(fig)

# Plot normalised slope parameters to identify outlying years and output to
# results folder - user can discard output for that year 
Example 35
Project: PyFluxPro   Author: OzFlux   File: pfp_cpd.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_slopes(df,d):
    df=df.reset_index(drop=True)
    if d["show_plots"]:
        plt.ion()
    else:
        plt.ioff()
    fig=plt.figure(figsize=(12,8))
    #fig.patch.set_facecolor('white')
    plt.scatter(df['norm_a1_median'],df['norm_a2_median'],s=80,edgecolors='blue',facecolors='none')
    plt.xlim(-4,4)
    plt.ylim(-4,4)
    plt.xlabel('$Median\/normalised\/ a^{1}$',fontsize=16)
    plt.ylabel('$Median\/normalised\/ a^{2}$',fontsize=16)
    plt.title('Normalised slope parameters \n')
    plt.axvline(x=1,color='black',linestyle='dotted')
    plt.axhline(y=0,color='black',linestyle='dotted')
    plot_out_name=os.path.join(d["plot_path"],d['site_name']+"_CPD_slopes.png")
    fig.savefig(plot_out_name)
    if d["show_plots"]:
        plt.draw()
        plt.ioff()
    else:
        plt.ion()
    #if d["call_mode"].lower()!="interactive": plt.close(fig)

#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
# Quality control within bootstrap 
Example 36
Project: adams   Author: bsvineethiitg   File: logger.py    MIT License 5 votes vote down vote up
def plot(self, imgname, names=None): 
        #print(self.names)
        names = self.names if names == None else names
        loss_names = [i if 'loss' in i.lower() else None for i in names]
        acc_names = [i if 'acc' in i.lower() else None for i in names]
        plt.ioff()
        numbers = self.numbers
        
        fig = plt.figure()
        lossnaam = []
        for _, name in enumerate(loss_names):
            if name is None:
                continue
            lossnaam.append(name)
            x = np.arange(len(numbers[name]))
            plt.plot(x, np.asarray(numbers[name]))
        plt.legend([self.title + '(' + name + ')' for name in lossnaam])
        plt.grid(True)
        plt.savefig(self.folderpath1 + '/loss-' + imgname)
        plt.close(fig)
        print('Plots saved at ' + self.folderpath1 + '/')
        
        fig = plt.figure()
        accnaam = []
        for _, name in enumerate(acc_names):
            if name is None:
                continue
            accnaam.append(name)
            x = np.arange(len(numbers[name]))
            plt.plot(x, np.asarray(numbers[name]))
        plt.legend([self.title + '(' + name + ')' for name in accnaam])
        plt.grid(True)
        plt.savefig(self.folderpath1 + '/acc-' + imgname)
        plt.close(fig)
        print('Plots saved at ' + self.folderpath1 + '/') 
Example 37
Project: industry-classifier   Author: xiedidan   File: plot.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_leakage(image_path, result):
    image = Image.open(image_path)
    image = transforms.functional.vflip(image)
    image = transforms.functional.to_tensor(image).numpy()
    image = np.transpose(image, (2, 1, 0))

    color = 'red'
    if result == 0:
        result = u'OK'
        color = 'lime'
    else:
        result = u'Leak'

    plt.ion()
    
    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5)

    plt.imshow(image)

    # plt.text(100, 500, result, color=color, fontsize=96)
    plt.xlabel(result, color=color, fontsize=96)

    plt.tight_layout()
    plt.ioff()

    plt.show() 
Example 38
Project: robust_physical_perturbations   Author: evtimovi   File: utils.py    MIT License 5 votes vote down vote up
def grid_visual(data):
    """
    This function displays a grid of images to show full misclassification
    :param data: grid data of the form;
        [nb_classes : nb_classes : img_rows : img_cols : nb_channels]
    :return: if necessary, the matplot figure to reuse
    """
    import matplotlib.pyplot as plt

    # Ensure interactive mode is disabled and initialize our graph
    plt.ioff()
    figure = plt.figure()
    figure.canvas.set_window_title('Cleverhans: Grid Visualization')

    # Add the images to the plot
    num_cols = data.shape[0]
    num_rows = data.shape[1]
    num_channels = data.shape[4]
    current_row = 0
    for y in xrange(num_rows):
        for x in xrange(num_cols):
            figure.add_subplot(num_cols, num_rows, (x + 1) + (y * num_rows))
            plt.axis('off')

            if num_channels == 1:
                plt.imshow(data[x, y, :, :, 0], cmap='gray')
            else:
                plt.imshow(data[x, y, :, :, :])

    # Draw the plot and return
    plt.show()
    return figure 
Example 39
Project: robust_physical_perturbations   Author: evtimovi   File: utils.py    MIT License 5 votes vote down vote up
def grid_visual(data):
    """
    This function displays a grid of images to show full misclassification
    :param data: grid data of the form;
        [nb_classes : nb_classes : img_rows : img_cols : nb_channels]
    :return: if necessary, the matplot figure to reuse
    """
    import matplotlib.pyplot as plt

    # Ensure interactive mode is disabled and initialize our graph
    plt.ioff()
    figure = plt.figure()
    figure.canvas.set_window_title('Cleverhans: Grid Visualization')

    # Add the images to the plot
    num_cols = data.shape[0]
    num_rows = data.shape[1]
    num_channels = data.shape[4]
    current_row = 0
    for y in xrange(num_rows):
        for x in xrange(num_cols):
            figure.add_subplot(num_cols, num_rows, (x + 1) + (y * num_rows))
            plt.axis('off')

            if num_channels == 1:
                plt.imshow(data[x, y, :, :, 0], cmap='gray')
            else:
                plt.imshow(data[x, y, :, :, :])

    # Draw the plot and return
    plt.show()
    return figure 
Example 40
Project: ptype-dmkd   Author: tahaceritli   File: utils.py    MIT License 5 votes vote down vote up
def _blob(x, y, area, colour):
    """
    Draws a square-shaped blob with the given area (< 1) at
    the given coordinates.
    """
    hs = np.sqrt(area) / 2
    xcorners = np.array([x - hs, x + hs, x + hs, x - hs])
    ycorners = np.array([y - hs, y - hs, y + hs, y + hs])
    plt.fill(xcorners, ycorners, colour, edgecolor=colour)



# def plot_hinton(W, method=None, _max_value=None, xticklabels=None, yticklabels=None, path=None):
#     """
#     Draws a Hinton diagram for visualizing a weight matrix.
#     Temporarily disables matplotlib interactive mode if it is on,
#     otherwise this takes forever.
#     """
#
#     reenable = False
#     if plt.isinteractive():
#         plt.ioff()
#     plt.clf()
#
#     if reenable:
#         plt.ion()
#
#     special.hinton(W, max_value=_max_value)
#     if xticklabels is not None:
#         plt.xticks(np.arange(len(xticklabels)), xticklabels, rotation=90, fontsize=13)
#     if yticklabels is not None:
#         plt.yticks(np.arange(len(xticklabels)), yticklabels, fontsize=13)
#
#     plt.xlabel('true type', fontsize=17)
#     plt.ylabel('predicted type', fontsize=17)
#
#     if path is not None:
#         plt.savefig(path, dpi=1000, bbox_inches="tight")
#
#     # plt.show() 
Example 41
Project: metatlas   Author: biorack   File: chromatograms_mp_plots.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_compounds_and_files_mp(kwargs):
    #print(mp.current_process())

    my_data= kwargs['data'] # data for all compounds for one file
    file_name  = kwargs['file_name'] # full path of output file name
    nRows, nCols = kwargs['rowscols']
    names = kwargs['names']
    share_y = kwargs['share_y']
    # plt.ioff()

    f,ax = plt.subplots(nRows, nCols, sharey=share_y,figsize=(8*nCols,nRows*6))
    ax = ax.flatten()
    plt.rcParams['pdf.fonttype']=42
    plt.rcParams['pdf.use14corefonts'] = True
#    matplotlib.rc('font', family='sans-serif') 
#    matplotlib.rc('font', serif='Helvetica') 
    plt.rcParams['text.usetex'] = False
    plt.rcParams.update({'font.size': 12})
    plt.rcParams.update({'font.weight': 'bold'})
    plt.rcParams['axes.linewidth'] = 2 # set the value globally
    
    for i,name in enumerate(names):
        plot_chromatogram(my_data[i], name, ax=ax[i])

    f.savefig(file_name)    
    plt.close(f) 
Example 42
Project: bmaml_rl   Author: jsikyoon   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def _enter_plotting(self, fontsize=9):
        """assumes that a figure is open """
        # interactive_status = matplotlib.is_interactive()
        self.original_fontsize = pyplot.rcParams['font.size']
        pyplot.rcParams['font.size'] = fontsize
        pyplot.hold(False)  # opens a figure window, if non exists
        pyplot.ioff() 
Example 43
Project: pyiron   Author: pyiron   File: gui.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_array(self, val):
        """

        Args:
            val:

        Returns:

        """
        try:
            import pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt

        plt.ioff()
        if self.fig is None:
            self.fig, self.ax = plt.subplots()
        else:
            self.ax.clear()

        # self.ax.set_title(self.name)
        if val.ndim == 1:
            self.ax.plot(val)
        elif val.ndim == 2:
            if len(val) == 1:
                self.ax.plot(val[0])
            else:
                self.ax.plot(val)
        elif val.ndim == 3:
            self.ax.plot(val[:, :, 0])
        # self.fig.canvas.draw()
        self.w_text.value = self.plot_to_html()
        plt.close() 
Example 44
Project: GProject   Author: fnbellomo   File: Plot.py    GNU General Public License v2.0 5 votes vote down vote up
def save_all_img(self,number_of_steps,plot_every_n,positions):
        """
        Method to save all plots to later make a animations
        """

        print('** Saving plots **')

        plt.ioff()
        plt.clf()
        self.fig, self.axes = plt.subplots(figsize=(12,12))

        #Check if are some img in the path.
        #If exist, delete all
        self.img_path = './Gravitation/Animation/Img/'
        if os.path.isdir(self.img_path):
            shutil.rmtree(self.img_path)
            os.mkdir(self.img_path)
        else:
            os.mkdir(self.img_path)

        self.img_num = 1
	
        self.base(True)
        for i in range(number_of_steps):
            if i%plot_every_n == 0:
                self.update(i,positions,True)

        print('** Converting plots **')
        os.system('mencoder mf:Gravitation/Animation/Img/*.jpg -mf w=800:h=600:fps=25:type=png -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o output.avi')
        print('** done **') 
Example 45
Project: srl-zoo   Author: araffin   File: representation_plot.py    MIT License 5 votes vote down vote up
def updateDisplayMode():
    """
    Enable or disable interactive plot
    see: http://matplotlib.org/faq/usage_faq.html#what-is-interactive-mode
    """
    if INTERACTIVE_PLOT:
        plt.ion()
    else:
        plt.ioff() 
Example 46
Project: DeepBayes   Author: deepgenerativeclassifier   File: utils.py    MIT License 5 votes vote down vote up
def grid_visual(data):
    """
    This function displays a grid of images to show full misclassification
    :param data: grid data of the form;
        [nb_classes : nb_classes : img_rows : img_cols : nb_channels]
    :return: if necessary, the matplot figure to reuse
    """
    import matplotlib.pyplot as plt

    # Ensure interactive mode is disabled and initialize our graph
    plt.ioff()
    figure = plt.figure()
    figure.canvas.set_window_title('Cleverhans: Grid Visualization')

    # Add the images to the plot
    num_cols = data.shape[0]
    num_rows = data.shape[1]
    num_channels = data.shape[4]
    current_row = 0
    for y in xrange(num_rows):
        for x in xrange(num_cols):
            figure.add_subplot(num_rows, num_cols, (x + 1) + (y * num_cols))
            plt.axis('off')

            if num_channels == 1:
                plt.imshow(data[x, y, :, :, 0], cmap='gray')
            else:
                plt.imshow(data[x, y, :, :, :])

    # Draw the plot and return
    plt.show()
    return figure 
Example 47
Project: pyffe   Author: fabiocarrara   File: liveplot.py    MIT License 5 votes vote down vote up
def waitclose(self):
        plt.ioff()
        plt.show() 
Example 48
Project: xenoGI   Author: ecbush   File: scores.py    GNU General Public License v3.0 5 votes vote down vote up
def plotScoreHists(paramD):
    """Wrapper to make pdf of histograms of scores."""

    import matplotlib.pyplot as pyplot
    from matplotlib.backends.backend_pdf import PdfPages
    from . import xenoGI
    
    numBins = 80 # num bins in histograms
    strainNamesT = xenoGI.readStrainInfoFN(paramD['strainInfoFN'])
    genesO = genomes.genes(paramD['geneInfoFN'])
    scoresO = readScores(strainNamesT,paramD['scoresFN'])
    aabrhHardCoreL = loadOrthos(paramD['aabrhFN'])
    
    def scoreHists(outFN,scoresO,numBins,scoreType,genesO,aabrhHardCoreL=None):
        '''Read through a scores file, and separate into all pairwise
comparisons. Then plot hist of each.'''

        # currently, this seems to require a display for interactive
        # plots. would be nice to make it run without that...

        pyplot.ioff() # turn off interactive mode
        with PdfPages(outFN) as pdf:
            for strainPair in scoresO.getStrainPairs():
                fig = pyplot.figure()
                scoresL = getScoresStrainPair(scoresO,strainPair,scoreType,genesO,aabrhHardCoreL)
                pyplot.hist(scoresL,bins=numBins, density = True, range = [0,1])
                pyplot.title(strainPair[0]+'-'+strainPair[1])
                pdf.savefig()
                pyplot.close()

    # plot histograms
    for scoreType,outFN in [('rawSc','rawSc.pdf'),('synSc','synSc.pdf'),('coreSynSc','coreSynSc.pdf'),]:
        scoreHists(outFN,scoresO,numBins,scoreType,genesO)

    for scoreType,outFN in [('rawSc','rawScHardCore.pdf'),('synSc','synScHardCore.pdf'),('coreSynSc','coreSynScHardCore.pdf'),]:
        scoreHists(outFN,scoresO,numBins,scoreType,genesO,aabrhHardCoreL) 
Example 49
Project: AiGEM_TeamHeidelberg2017   Author: igemsoftware2017   File: helpers.py    MIT License 5 votes vote down vote up
def plot_simple_curve(self, x, y, title, legend, xname, yname, filename, include_linear=True, iGEM_style=True):
        """Plots simple curve in the iGEM style if wanted.

        Args:
          x: `Array1d`, what to plot on the x-Axis.
          y: `Array1d` what to plot on the y-Axis.
          title: `str`, the title.
          legend:`str`, the legend.
          xname: `str`, the name of the x axis.
          yname: `str`, the name of the y axis.
          filename: `str`, path to the file where to save the plot.
          include_linear: `bool`, whether to plot a linear line with slope=1.
          iGEM_style: `bool`, whether to plot in the iGEM-Heidelberg style layout.
        """
        plt.ioff()
        fig = plt.figure(1, figsize=(5, 5), dpi=200)
        plt.plot(x, y, color='#005493', lw=2, label=legend)
        if include_linear:
            plt.plot([0, 1], [0, 1], color='#B9B9B9', lw=2, linestyle="--")
        plt.xlim([0.0, 1.0])
        plt.ylim([0.0, 1.05])
        if iGEM_style:
            plt.title(title, fontproperties=self.font)
            plt.xlabel(xname, fontproperties=self.font)
            plt.ylabel(yname, fontproperties=self.font)
            plt.legend(loc="lower right", prop=self.font)
        else:
            plt.title(title)
            plt.xlabel(xname)
            plt.ylabel(yname)
            plt.legend(loc="lower right")

        plt.savefig(filename+".svg")
        plt.savefig(filename+".png")
        plt.close(fig) 
Example 50
Project: AiGEM_TeamHeidelberg2017   Author: igemsoftware2017   File: helpers.py    MIT License 5 votes vote down vote up
def plot_simple_curve(x, y, title, legend, xname, yname, filename):
    plt.ioff()
    fig = plt.figure()
    plt.title(title)
    plt.plot(x, y, color="red", lw=2, label=legend)
    plt.plot([0, 1], [0, 1], color="navy", lw=2, linestyle="--")
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel(xname)
    plt.ylabel(yname)
    plt.legend(loc="lower right")
    plt.savefig(filename+".svg")
    plt.savefig(filename+".png")
    plt.close(fig)