Python matplotlib.pyplot 模块,ioff() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.ioff()

项目:xenoGI    作者:ecbush    | 项目源码 | 文件源码
def scoreHists(scoresFN,outFN,numBins,geneNames,scoreType):
    '''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...

    pairD = readScorePairs(scoresFN,geneNames,scoreType)

    pyplot.ioff() # turn off interactive mode
    with PdfPages(outFN) as pdf:
        for key in pairD:
            fig = pyplot.figure()
            pyplot.hist(pairD[key],bins=numBins)
            pyplot.title('-'.join(key))
            pdf.savefig()
            pyplot.close()
项目:TemporalEncoding    作者:SpikeFrame    | 项目源码 | 文件源码
def plot_spikepattern(spike_trains, sim_time):
    """Plot set of spike trains (spike pattern)"""
    plt.ioff()

    plt.figure()
    for i in xrange(len(spike_trains)):
        spike_times = spike_trains[i].value
        plt.plot(spike_times, np.full(len(spike_times), i,
                 dtype=np.int), 'k.')
    plt.xlim((0.0, sim_time))
    plt.ylim((0, len(spike_trains)))
    plt.xlabel('Time (ms)')
    plt.ylabel('Neuron index')
    plt.show()

    plt.ion()
项目:TemporalEncoding    作者:SpikeFrame    | 项目源码 | 文件源码
def plot_spiker(record, spike_trains_target, neuron_index=0):
    """Plot spikeraster and target timings for given neuron index"""
    plt.ioff()

    spike_trains = [np.array(i.spiketrains[neuron_index])
                    for i in record.segments]
    n_segments = record.size['segments']

    plt.figure()
    for i in xrange(len(spike_trains)):
        plt.plot(spike_trains[i], np.full(len(spike_trains[i]), i + 1,
                 dtype=np.int), 'k.')
    target_timings = spike_trains_target[neuron_index].value
    plt.plot(target_timings, np.full(len(target_timings), 1.025 * n_segments),
             'kx', markersize=8, markeredgewidth=2)
    plt.xlim((0., np.float(record.segments[0].t_stop)))
    plt.ylim((0, np.int(1.05 * n_segments)))
    plt.xlabel('Time (ms)')
    plt.ylabel('Trials')
    plt.title('Output neuron {}'.format(neuron_index))
    plt.show()

    plt.ion()
项目:pystudio    作者:satorchi    | 项目源码 | 文件源码
def setup_plot_iv_multi(self,nrows=16,ncols=8,xwin=True):
    if not isinstance(self.vbias,np.ndarray): self.vbias=make_Vbias()
    ttl=str('QUBIC I-V curves (%s)' % (self.obsdate.strftime('%Y-%b-%d %H:%M UTC')))

    nbad=0
    for val in self.is_good_iv():
        if not val:nbad+=1
    ttl+=str('\n%i flagged as bad pixels' % nbad)

    if xwin: plt.ion()
    else: plt.ioff()
    fig,axes=plt.subplots(nrows,ncols,sharex=True,sharey=False,figsize=self.figsize)
    if xwin: fig.canvas.set_window_title('plt: '+ttl)
    fig.suptitle(ttl,fontsize=16)
    plt.xlabel('Bias Voltage  /  V')
    plt.ylabel('Current  /  $\mu$A')
    return fig,axes
项目:pystudio    作者:satorchi    | 项目源码 | 文件源码
def setup_plot_iv(self,TES,xwin=True):
    ttl=str('QUBIC I-V curve for TES#%3i (%s)' % (TES,self.obsdate.strftime('%Y-%b-%d %H:%M UTC')))
    if self.temperature==None:
        tempstr='unknown'
    else:
        tempstr=str('%.0f mK' % (1000*self.temperature))
    subttl=str('Array %s, ASIC #%i, Pixel #%i, Temperature %s' % (self.detector_name,self.asic,self.tes2pix(TES),tempstr))
    if xwin: plt.ion()
    else: plt.ioff()
    fig=plt.figure(figsize=self.figsize)
    fig.canvas.set_window_title('plt: '+ttl) 
    fig.suptitle(ttl+'\n'+subttl,fontsize=16)
    ax=plt.gca()
    ax.set_xlabel('Bias Voltage  /  V')
    ax.set_ylabel('Current  /  $\mu$A')
    ax.set_xlim([self.bias_factor*self.min_bias,self.bias_factor*self.max_bias])
    return fig,ax
项目:smp_base    作者:x75    | 项目源码 | 文件源码
def set_interactive(interactive = False):
    """This function does something.

    Args:
       name (str):  The name to use.

    Kwargs:
       state (bool): Current state to be in.

    Returns:
       int.  The return code::

          0 -- Success!
          1 -- No good.
          2 -- Try again.

    Raises:
       AttributeError, KeyError
     """
    if interactive:
        plt.ion()
    else:
        plt.ioff()
项目:smp_base    作者:x75    | 项目源码 | 文件源码
def plot_scattermatrix(df, **kwargs):
    """plot a scattermatrix from dataframe
    """
    if df is None:
        logger.log(loglevel_debug, "plot_scattermatrix: no data passed")
        return

    # df = pd.DataFrame(X, columns=['x1_t', 'x2_t', 'x1_tptau', 'x2_tptau', 'u_t'])
    # scatter_data_raw = np.hstack((np.array(Xs), np.array(Ys)))
    # scatter_data_raw = np.hstack((Xs, Ys))
    # logger.log(loglevel_debug, "scatter_data_raw", scatter_data_raw.shape)

    plt.ioff()
    # df = pd.DataFrame(scatter_data_raw, columns=["x_%d" % i for i in range(scatter_data_raw.shape[1])])
    sm = scatter_matrix(df, ax = kwargs['ax'], alpha=0.2, figsize=(10, 10), diagonal='hist')
    print type(sm), sm.shape, sm[0,0]
    # fig = sm[0,0].get_figure()
    # if SAVEPLOTS:
    # fig.savefig("fig_%03d_scattermatrix.pdf" % (fig.number), dpi=300)
    # fig.show()
    # plt.show()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def _plot_single_map1(self, path, cmap, signo, dist_map, threshold, constrained, stretch, colorMap, suffix):
        import matplotlib.pyplot as plt
        if path != None:
            plt.ioff()
        grad = self.get_single_map(signo, cmap, dist_map, threshold, constrained, stretch)
        plt.imshow(grad, interpolation='none')
        plt.set_cmap(colorMap)
        cbar = plt.colorbar()
        cbar.set_ticks([])
        if path != None:
            if suffix == None:
                fout = osp.join(path, '{0}_{1}.png'.format(self.label, signo))
            else:
                fout = osp.join(path, '{0}_{1}_{2}.png'.format(self.label, signo, suffix))
            try:
                plt.savefig(fout)
            except IOError:
                raise IOError('in classifiers.output, no such file or directory: {0}'.format(path))
        else:
            if suffix == None:
                plt.title('{0} - EM{1}'.format(self.label, signo))
            else:
                plt.title('{0} - EM{1} - {2}'.format(self.label, signo, suffix))
            plt.show()
        plt.close()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def tests():
    plt.ioff()
    data_path = os.environ['PYSPTOOLS_DATA']
    home = os.environ['HOME']
    result_path = osp.join(home, 'results')
    if osp.exists(result_path) == False:
        os.makedirs(result_path)

    fin = open(os.path.join(data_path, 'dnagwas.txt'))
    signal_txt = fin.readlines()
    signal = [float(x) for x in signal_txt]
    z = sig.bilateral(np.array(signal), 0, 10, 25, display=1, maxiter=5)
    plt.plot(signal)
    plt.plot(z, color='r')
    if os.path.exists(result_path) == False:
        os.makedirs(result_path)
    plt.savefig(os.path.join(result_path, 'dnagwas.png'))
项目:synchrony    作者:cknd    | 项目源码 | 文件源码
def viewanim(data,start=0,skip=2,title=None,cmap='bone', ms_per_step=None):
    """
    Show an animation of a single simulation run, each node
    represented (via its node label) as pixel (i,j) in an MxN image.
    So this will only be useful for grid graphs.

    Args:
        data: MxNxT array of voltage traces
        start: first timestep to show
        skip: timesteps to advance in each frame (higher -> faster)
        title: figure title
        cmap: matplotlib colormap (name OR object)
    """
    #plt.ioff()
    anim = createanim(data,start,skip,title=title,cmap=cmap, ms_per_step=ms_per_step)
    plt.show()
    plt.ion()
项目:mrflow    作者:jswulff    | 项目源码 | 文件源码
def plot_quiver(pt, uv, title, masks=None, norm=-1, outpath='.'):
    if plt is None:
        return
    plt.ioff()
    if masks is None:
        masks = [np.ones(pt.shape[0])>0,]
    if norm > 0:
        uvlen = np.sqrt((uv**2).sum(axis=1))
        uv[uvlen<norm,:] /= (1.0/norm) * uvlen[uvlen<norm][:,np.newaxis]
    colors = ['r','b','g','c','y']
    plt.figure()
    for i,m in enumerate(masks):
        plt.quiver(pt[m,0],
                pt[m,1],
                uv[m,0],
                uv[m,1],
                color=colors[i%len(colors)],
                angles='xy',
                scale_units='xy',
                scale=1)

    plt.axis('equal')
    plt.title(title)
    plt.ylim([pt[:,1].max(),0])
    save_figure(title, outpath)
项目:mrflow    作者:jswulff    | 项目源码 | 文件源码
def plot_plot(y, title, legends=None,outpath='.'):
    if plt is None:
        return
    if np.array(y).ndim == 1:
        y = np.array(y).reshape((-1,1))
    no_legends = legends is None
    if legends is None or len(legends) < y.shape[1]:
        legends = [''] * y.shape[1]
    plt.ioff()
    plt.figure()
    for d in range(y.shape[1]):
        plt.plot(y[:,d],label=legends[d])
    if not no_legends:
        plt.legend()
    plt.title(title)
    save_figure(title,outpath)
项目:autoxd    作者:nessessary    | 项目源码 | 文件源码
def _test_AsynDrawKline(self):
        code = '300033'
        start_day = '2017-8-25'
        #df = stock.getHisdatDataFrameFromRedis(code, start_day)
        df = stock.getFiveHisdatDf(code, start_day=start_day)
        import account
        account = account.LocalAcount(account.BackTesting())
        #????????
        indexs = agl.GenRandomArray(len(df), 3)
        trade_bSell = [0,1,0]
        df_trades = df[df.index.map(lambda x: x in df.index[indexs])]
        df_trades = df_trades.copy()
        df_trades[AsynDrawKline.enum.trade_bSell] = trade_bSell

        plt.ion()
        for i in range(10):
            AsynDrawKline.drawKline(df[i*10:], df_trades)

        plt.ioff()
        #plt.show()  #???????? ????????
项目:infusion    作者:jiamings    | 项目源码 | 文件源码
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)
项目:infusion    作者:jiamings    | 项目源码 | 文件源码
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)
项目:PyIPOL    作者:martinResearch    | 项目源码 | 文件源码
def example():

   from matplotlib import pyplot as plt
   import cv2
   im_file =wrapper.source_directory+'/wrench.bmp'
   image=cv2.imread(im_file)# the scipy.misc.imread uses PIL which give an error for this bmp file (Unsupported BMP compression )
   output,animation=wrapper.chanvese(image)
   plt.ion()
   for frame in  animation:
      plt.imshow(frame)
      plt.draw()
      plt.show()
   plt.ioff()
   plt.imshow(output, cmap='Greys_r')
   plt.show()
   print 'done'
项目:PyIPOL    作者:martinResearch    | 项目源码 | 文件源码
def example():
    plt.ion()

    im_file =os.path.join(lsd.source_directory,'chairs.pgm')
    print 'reading file %s'%im_file
    #image =imread(im_file)# does not work with the provided pgm file :(

    image=netpbmfile.imread(im_file)
    plt.subplot(1,2,1)
    plt.imshow(image,cmap=plt.cm.Greys_r)

    segments=lsd.lsd(image)
    print 'found '+str( segments.shape[0]),' segments'


    #plt.ion()
    plt.subplot(1,2,2)
    plt.imshow(image,cmap=plt.cm.Greys_r)
    for seg in segments:
        plt.plot(seg[[0,2]],seg[[1,3]])
    plt.axis('tight')
    plt.ioff()

    plt.show()
项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
def _enter_plotting(self, fontsize=7):
        """assumes that a figure is open """
        from matplotlib import pyplot
        # interactive_status = matplotlib.is_interactive()
        self.original_fontsize = pyplot.rcParams['font.size']
        # if font size deviates from default, we assume this is on purpose and hence leave it alone
        if pyplot.rcParams['font.size'] == pyplot.rcParamsDefault['font.size']:
            pyplot.rcParams['font.size'] = fontsize
        # was: pyplot.hold(False)
        # pyplot.gcf().clear()  # opens a figure window, if non exists
        pyplot.ioff()
项目:structured-output-ae    作者:sbelharbi    | 项目源码 | 文件源码
def superpose(cdfs, outputpath, data):
    border_x = 0.5
    dx = 0.001
    x = np.arange(0, border_x, dx)
    plt.ioff()
    fig = plt.figure(figsize=(10,8))
    plt.xticks([0.01, 0.02, 0.05, 0.07, 0.09, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5])
    plt.yticks([0.1, 0.2, 0.3, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0])
    plt.xticks(rotation=70)
    plt.grid(b=True, which='major', axis='both', linestyle='dotted')
    floating = 3
    prec = "%." + str(floating) + "f"
    for cdf in cdfs:
        title = cdf["title"]
        auc = cdf["auc"]
        cdf01 = cdf["cdf01"]
        cdf_val = cdf["cdf"]
        plt.plot(x, cdf_val, marker=',',
                 label=title + ", CDF(0.1)=" + str(prec % (cdf01*100)) + "%, AUC=" +
                 str(prec % np.float(auc)) + "%")
    plt.legend(loc=4, prop={'size': 8}, fancybox=True, shadow=True)
    fig.suptitle('Cumulative distribution function (CDF) of NRMSE over ' + data + ' test set.')
    plt.xlabel('NRMSE')
    plt.ylabel('Data proportion')
    fig.savefig(outputpath, bbox_inches='tight', format='eps', dpi=1000)
    plt.ion()
项目:structured-output-ae    作者:sbelharbi    | 项目源码 | 文件源码
def show_landmarks_unit_test(self, im, phis_pred, phis_mean_train, bbox, save=False, path="../im.png"):
        """ Display a shape over the face image. (python)


        phis_pred: predicted phis [xxxyyy]
        phis_mean_train: mean phis of ground of truth
        bbox=[x y w h]
        im = np.ndarray
        """
        plt.close('all')
        if save:
            plt.ioff()

        nfids = int(len(phis_pred)/2)
        plt.imshow(im, cmap = cm.Greys_r)
        gt = plt.scatter(x=phis_mean_train[0:nfids], y=phis_mean_train[nfids:], c='g', s=40)
        pr = plt.scatter(x=phis_pred[0:nfids], y=phis_pred[nfids:], c='r', s=20)

        mse = np.mean(np.power((phis_pred - phis_mean_train), 2))
        plt.legend((gt, pr), ("mean shape train", "prediction, MSE="+str(mse)), scatterpoints=1,loc='lower left', fontsize=8, fancybox=True, shadow=True)
        """
        plt.plot([bbox[0], bbox[0]],[bbox[1],bbox[1]+bbox[3]],'-b', linewidth=1)
        plt.plot([bbox[0], bbox[0]+bbox[2]],[bbox[1], bbox[1]],'-b', linewidth=1)
        plt.plot([bbox[0]+bbox[2], bbox[0]+bbox[2]],[bbox[1], bbox[1]+bbox[3]],'-b', linewidth=1)
        plt.plot([bbox[0] ,bbox[0]+bbox[2]],[bbox[1]+bbox[3] ,bbox[1]+bbox[3]],'-b', linewidth=1)
        """
        plt.axis('off')

        if save:
            plt.savefig(path,bbox_inches='tight', dpi=1000)
            plt.ion()
        else:
            plt.show()
            raw_input("... Press ENTER to continue,")

        plt.close('all')
项目:cleverhans    作者:tensorflow    | 项目源码 | 文件源码
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
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
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()
项目:TemporalEncoding    作者:SpikeFrame    | 项目源码 | 文件源码
def plot_error(err):
    """Plot error with each epoch"""
    plt.ioff()

    plt.figure()
    plt.plot(1 + np.arange(len(err)), err, 'k-', linewidth=1)
    plt.xlabel('Epochs')
    plt.ylabel('van Rossum distance')
    plt.grid()
    plt.show()

    plt.ion()
项目:sympl    作者:mcgibbon    | 项目源码 | 文件源码
def __init__(self, plot_function, interactive=True):
        """
        Initialize a PlotFunctionMonitor.

        Args
        ----
        plot_function : func
            A function plot_function(fig, state) that
            draws the given state onto the given (initially clear) figure.
        interactive: bool, optional
            If true, matplotlib's interactive mode will be enabled,
            allowing plot animation while other computation is running.
        """
        global plt
        try:
            import matplotlib.pyplot as plt
        except ImportError:
            raise DependencyError(
                'matplotlib must be installed to use PlotFunctionMonitor')
        if interactive:
            plt.ion()
            self._fig = plt.figure()
        else:
            plt.ioff()
            self._fig = None
        self._plot_function = plot_function
项目:bifrost    作者:ledatelescope    | 项目源码 | 文件源码
def save_waterfall_plot(self, waterfall_matrix):
        """Save an image of the waterfall plot using
            thread-safe backend for pyplot, and labelling
            the plot using the header information from the
            ring
        @param[in] waterfall_matrix x axis is frequency and
            y axis is time. Values should be power.
            """
        import matplotlib
        # Use a graphical backend which supports threading
        matplotlib.use('Agg')
        from matplotlib import pyplot as plt
        plt.ioff()
        print "Interactive mode off"
        print waterfall_matrix.shape
        fig = pylab.figure()
        ax = fig.gca()
        header = self.header
        ax.set_xticks(
            np.arange(0, 1.33, 0.33) * waterfall_matrix.shape[1])
        ax.set_xticklabels(
            header['fch1'] - np.arange(0, 4) * header['foff'])
        ax.set_xlabel("Frequency [MHz]")
        ax.set_yticks(
            np.arange(0, 1.125, 0.125) * waterfall_matrix.shape[0])
        ax.set_yticklabels(
            header['tstart'] + header['tsamp'] * np.arange(0, 1.125, 0.125) * waterfall_matrix.shape[0])
        ax.set_ylabel("Time (s)")
        plt.pcolormesh(
            waterfall_matrix, axes=ax, figure=fig)
        fig.autofmt_xdate()
        fig.savefig(
            self.imagename, bbox_inches='tight')
        plt.close(fig)
项目:pystudio    作者:satorchi    | 项目源码 | 文件源码
def plot_pv(self,TES,xwin=True):
    ttl=str('QUBIC P-V curve for TES#%3i (%s)' % (TES,self.obsdate.strftime('%Y-%b-%d %H:%M UTC')))
    if self.temperature==None:
        tempstr='unknown'
    else:
        tempstr=str('%.0f mK' % (1000*self.temperature))
    subttl=str('Array %s, ASIC #%i, Pixel #%i, Temperature %s' % (self.detector_name,self.asic,self.tes2pix(TES),tempstr))
    if xwin: plt.ion()
    else: plt.ioff()
    fig,ax=plt.subplots(1,1,figsize=self.figsize)
    fig.canvas.set_window_title('plt: '+ttl) 
    fig.suptitle(ttl+'\n'+subttl,fontsize=16)
    ax.set_xlabel('Bias Voltage  /  V')
    ax.set_ylabel('P$_\mathrm{TES}$  /  $p$A')
    ax.set_xlim([self.bias_factor*self.min_bias,self.bias_factor*self.max_bias])

    istart,iend=self.selected_iv_curve(TES)
    Ptes=self.Ptes(TES)[istart:iend]
    bias=self.bias_factor*self.vbias[istart:iend]
    plt.plot(bias,Ptes)

    pngname=str('TES%03i_PV_array-%s_ASIC%i_%s.png' % (TES,self.detector_name,self.asic,self.obsdate.strftime('%Y%m%dT%H%M%SUTC')))
    pngname_fullpath=self.output_filename(pngname)
    if isinstance(pngname_fullpath,str): plt.savefig(pngname_fullpath,format='png',dpi=100,bbox_inches='tight')
    if xwin: plt.show()
    else: plt.close('all')
    return fig,ax
项目:rllabplusplus    作者:shaneshixiang    | 项目源码 | 文件源码
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()
项目:cma    作者:hardmaru    | 项目源码 | 文件源码
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()
项目:tfnn    作者:MorvanZhou    | 项目源码 | 文件源码
def hold_plot():
        print('Press any key to exit...')
        plt.ioff()
        plt.waitforbuttonpress()
        plt.close()
项目:deep-learning-with-Keras    作者:decordoba    | 项目源码 | 文件源码
def on_train_end(self, logs={}):
        self.update_epoch_plots(rescale_Y=True)  # Rescales Y in epoch plots
        if SHOW_PLOTS:
            plt.ioff()  # Make plots blocking again
        else:
            self.epoch_fig.clear()
            try:
                self.batch_fig.clear()
            except AttributeError:
                pass
项目:deep-learning-with-Keras    作者:decordoba    | 项目源码 | 文件源码
def plot_two_images(images1, images2, fig_num=0, title1=None, title2=None,
                    cmap="Greys", no_axis=True, invert_colors=False, suptitle=None):
    """
    Show all images in images1 and images2 list, one at a time side by side, waiting for an
    ENTER to show the next one. If q + ENTER is pressed, the function is terminated

    params: images1 and images2 are the list of images to show, fig_num is the
            figure number that will be used, title1 and title2 are the titles that will be shown
            over their respective images, cmap is the color map used, no_axis will hide the axis,
            suptitle will be the title of the whole figure
    """
    titles = []
    titles += [""] if title1 is None else [title1]
    titles += [""] if title2 is None else [title2]
    if titles == ["", ""]:
        titles = None
    plt.ion()  # Allows plots to be non-blocking
    fig = plt.figure(fig_num)
    fig.clear()
    for img1, img2 in zip(images1, images2):
        plot_all_images([img1, img2], fig_num=fig_num, filename=None, labels=titles,
                        label_description=None, cmap=cmap, no_axis=no_axis,
                        suptitle=suptitle, invert_colors=invert_colors)
        plt.pause(0.001)
        s = input("Press ENTER to see the next image, or Q (q) to continue:  ")
        if len(s) > 0 and s[0].lower() == "q":
            break
    fig.clear()
    plt.close()  # Hide plotting window
    plt.ioff()  # Make plots blocking again
项目:deep-learning-with-Keras    作者:decordoba    | 项目源码 | 文件源码
def plot_weights(w, fig_num=0, filename=None, title=None, cmap=None):
    """
    Show weights of a 3D or 4D kernel.
    Dim0, Dim1: (x, y),
    Dim2: depth,
    Dim3: #kernels

    If w has only 3D, it is assumed that Dim2 is the #kernels, and depth is 1 (B/W kernels).
    If depths is different to 3 or 4, depth is set to 1, and only the 1st component is used

    If filename is None, the figure will be shown, otherwise it will be saved with name filename
    """
    num_imgs = 1
    if w.ndim == 4:
        num_imgs = w.shape[3]
        num_colors = w.shape[2]
        if num_colors < 3:
            w = w[:, :, 0, :]
        elif num_colors > 4:
            print("Too many dimensions, ignoring all but the first one")
            w = w[:, :, 0, :]
    elif w.ndim == 3:
        num_imgs = w.shape[2]
    NUM_ROWS = math.floor(num_imgs ** 0.5)
    NUM_COLS = math.ceil(num_imgs ** 0.5)
    if NUM_ROWS * NUM_COLS < num_imgs:
        NUM_ROWS += 1
    if filename is None:
        plt.ion()
    fig = plt.figure(fig_num)
    if title is not None:
        fig.suptitle(title)
    for i in range(num_imgs):
        subfig = fig.add_subplot(NUM_ROWS, NUM_COLS, i + 1)
        subfig.imshow(w[:, :, i], cmap=cmap)
        subfig.axis('off')
    if filename is None:
        plt.ioff()
    else:
        fig.savefig(filename, bbox_inches="tight")
        fig.clear()
项目:deep-learning-with-Keras    作者:decordoba    | 项目源码 | 文件源码
def plot_history(history, fig_num=0, filename=None):
    """
    Plots loss and accuracy in history
    If filename is None, the figure will be shown, otherwise it will be saved with name filename
    """
    # Plot epoch history for accuracy and loss
    if filename is None:
        plt.ion()
    fig = plt.figure(fig_num)
    subfig = fig.add_subplot(122)
    subfig.plot(history.history['acc'], label="training")
    if history.history['val_acc'] is not None:
        subfig.plot(history.history['val_acc'], label="validation")
    subfig.set_title('Model Accuracy')
    subfig.set_xlabel('Epoch')
    subfig.legend(loc='upper left')
    subfig = fig.add_subplot(121)
    subfig.plot(history.history['loss'], label="training")
    if history.history['val_loss'] is not None:
        subfig.plot(history.history['val_loss'], label="validation")
    subfig.set_title('Model Loss')
    subfig.set_xlabel('Epoch')
    subfig.legend(loc='upper left')
    if filename is None:
        plt.ioff()
    else:
        fig.savefig(filename, bbox_inches="tight")
        fig.clear()
项目:deep-learning-with-Keras    作者:decordoba    | 项目源码 | 文件源码
def plot_weights(w, fig_num=0, title=None, cmap=None):
    """ Show weights of 3D or 4D kernel. Dim0, Dim1: (x, y), Dim2: depth, Dim3: #examples """
    num_imgs = 1
    if w.ndim == 4:
        num_imgs = w.shape[3]
        num_colors = w.shape[2]
        if num_colors < 3:
            w = w[:, :, 0, :]
        elif num_colors > 4:
            print("Too many dimensions, ignoring all bot the first one")
            w = w[:, :, 0, :]
    elif w.ndim == 3:
        num_imgs = w.shape[2]
    NUM_ROWS = math.floor(num_imgs ** 0.5)
    NUM_COLS = math.ceil(num_imgs ** 0.5)
    if NUM_ROWS * NUM_COLS < num_imgs:
        NUM_ROWS += 1
    plt.ion()
    fig = plt.figure(fig_num)
    if title is not None:
        fig.suptitle(title)
    for i in range(num_imgs):
        subfig = fig.add_subplot(NUM_ROWS, NUM_COLS, + i + 1)
        subfig.imshow(w[:, :, i], cmap=cmap)
        subfig.axis('off')
    plt.ioff()
项目:deep-learning-with-Keras    作者:decordoba    | 项目源码 | 文件源码
def on_train_end(self, logs={}):
        # for fig in self.figs:
        #     if fig is not None and fig.canvas.manager.window is not None:
        #         fig.show()
        plt.ioff()  # Make plots blocking again
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def _plot_target_map(path, tmap, map_type, whiteOnBlack, suffix=None):
    """ Plot a target map using matplotlib """
    import matplotlib.pyplot as plt
    import os.path as osp
    if path != None:
        plt.ioff()
    img = plt.imshow(tmap)
    if whiteOnBlack == True:
        img.set_cmap('Greys_r')
    elif whiteOnBlack == False:
        img.set_cmap('Greys')
    else:
        # throw an error?
        img.set_cmap('Blues')
    if path != None:
        if suffix == None:
            fout = osp.join(path, 'tmap_{0}.png'.format(map_type))
        else:
            fout = osp.join(path, 'tmap_{0}_{1}.png'.format(map_type, suffix))
        try:
            plt.savefig(fout)
        except IOError:
            raise IOError('in detection._plot_target_map, no such file or directory: {0}'.format(path))
    else:
        if suffix == None:
            plt.title('{0} Target Map'.format(map_type))
        else:
            plt.title('{0} Target Map - {1}'.format(map_type, suffix))
            plt.show()
    plt.clf()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def plot1(self, img, path=None, mask=None, interpolation='none', colorMap='jet', suffix=''):
        import matplotlib.pyplot as plt
        if path != None:
            plt.ioff()

        if isinstance(mask, np.ndarray):
            img = img[:,:] * mask

        plt.imshow(img, interpolation=interpolation)
        plt.set_cmap(colorMap)
        cbar = plt.colorbar()
        cbar.set_ticks([])
        if path != None:
            if suffix == None:
                fout = osp.join(path, '{0}.png'.format(self.label))
            else:
                fout = osp.join(path, '{0}_{1}.png'.format(self.label, suffix))
            try:
                plt.savefig(fout)
            except IOError:
                raise IOError('in classifiers.output, no such file or directory: {0}'.format(path))
        else:
            if suffix == None:
                plt.title('{0}'.format(self.label))
            else:
                plt.title('{0} - {1}'.format(self.label, suffix))
            plt.show()

        plt.close()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def plot_histo(self, path, cmap, em_nbr, suffix):
        import matplotlib.pyplot as plt
        plt.ioff()
        farray = np.ndarray.flatten(cmap)
        plt.hist(farray, bins=range(em_nbr+2), align='left')
        if suffix == None:
            fout = osp.join(path, 'histo_{0}.png'.format(self.label))
        else:
            fout = osp.join(path, 'histo_{0}_{1}.png'.format(self.label, suffix))
        try:
            plt.savefig(fout)
        except IOError:
            raise IOError('in classifiers.output, no such file or directory: {0}'.format(path))
        plt.close()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def plot(self, path, plot_name, suffix=None):
        """
        Plot the hull quotient graph using matplotlib.

        Parameters:
            path: `string`
              The path where to put the plot.

            plot_name: `string`
              File name.

            suffix: `string`
              Add a suffix to the file name.
        """
        import os.path as osp
        import matplotlib.pyplot as plt
        plt.ioff()
        if suffix == None:
            fout = osp.join(path, plot_name + '.png')
        else:
            fout = osp.join(path, plot_name + '_{0}.png'.format(suffix))
        plt.xlabel('Wavelength')
        plt.ylabel('Brightness')
        plt.title('{0} Hull Quotient'.format(plot_name))
        plt.grid(True)
        plt.plot(self.wvl, self.crs, 'g', label='crs')
        plt.plot(self.hx, self.hy, 'c', label='hull')
        plt.plot(self.hx, self.hy, 'r.', label='hull pts')
        plt.plot(self.wvl, self.spectrum, 'b', label='signal')
        plt.legend(framealpha=0.5)
        plt.savefig(fout)
        plt.close()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def plot(image, colormap, desc, path):
    plt.ioff()
    img = plt.imshow(image, interpolation='none')
    img.set_cmap(colormap)
    plt.colorbar()
    fout = osp.join(path, '{0}.png'.format(desc))
    plt.savefig(fout)
    plt.clf()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def plot_synthetic_image(image, colormap, desc, result_path):
    plt.ioff()
    img = plt.imshow(image, interpolation='none')
    img.set_cmap(colormap)
    plt.colorbar()
    fout = osp.join(result_path, 'synthetic_{0}.png'.format(desc))
    plt.savefig(fout)
    plt.clf()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def plot(image, colormap, desc, path):
    plt.ioff()
    img = plt.imshow(image, interpolation='none')
    img.set_cmap(colormap)
    plt.colorbar()
    fout = osp.join(path, 'plot_{0}.png'.format(desc))
    plt.savefig(fout)
    plt.clf()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def plot(image, colormap, desc, path):
    import matplotlib.pyplot as plt
    plt.ioff()
    img = plt.imshow(image, interpolation='none')
    img.set_cmap(colormap)
    plt.colorbar()
    fout = osp.join(path, 'plot_{0}.png'.format(desc))
    plt.savefig(fout)
    plt.clf()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def plot_bands_sample(self, path, band_no, suffix=None):
        """
        Plot a filtered band.

        Parameters:
            path: `string`
              The path where to put the plot.

            band_no: `int or string`
                The band index.
                If band_no == 'all', plot all the bands.

            suffix: `string [default None]`
              Add a suffix to the file name.
        """
        import matplotlib.pyplot as plt
        plt.ioff()
        if band_no == 'all':
            for i in range(self.dbands.shape[2]):
                plt.imshow(self.dbands[:,:,i], interpolation='none')
                if suffix == None:
                    fout = osp.join(path, 'SavitzkyGolay_band_{0}.png'.format(i))
                else:
                    fout = osp.join(path, 'SavitzkyGolay_band_{0}_{1}.png'.format(i, suffix))
                plt.savefig(fout)
                plt.close()
        else:
            plt.imshow(self.dbands[:,:,band_no], interpolation='none')
            if suffix == None:
                fout = osp.join(path, 'SavitzkyGolay_band_{0}.png'.format(band_no))
            else:
                fout = osp.join(path, 'SavitzkyGolay_band_{0}_{1}.png'.format(band_no, suffix))
            plt.savefig(fout)
            plt.close()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def plot_components(self, path, n_first=None, colorMap='jet', suffix=None):
        """
        Plot some bands.

        Parameters:
            path: `string`
              The path where to put the plot.

            n_first: `int [default None]`
                Print the first n components.

            colorMap: `string [default jet]`
              A matplotlib color map.

            suffix: `string [default None]`
              Suffix to add to the title.
        """
        import matplotlib.pyplot as plt
        if n_first != None:
            n = min(n_first, self.mnf.shape[2])
        else:
            n = self.mnf.shape[2]
        plt.ioff()
        for i in range(n):
            plt.imshow(self.mnf[:,:,i], interpolation='none', cmap=colorMap)
            if suffix == None:
                fout = osp.join(path, 'MNF_bandno_{0}.png'.format(i+1))
            else:
                fout = osp.join(path, 'MNF_bandno_{0}_{1}.png'.format(i+1, suffix))
            plt.savefig(fout)
            plt.clf()
        plt.close()
项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
def plot_linear_stretch(M, path, R, G, B, suffix=None):
    """
    Plot a linear stretched RGB image.

    Parameters:
        M: `numpy array`
          A HSI cube (m x n x p).

        path: `string`
          The path where to put the plot.

        R: `int`
            A band number that will render the red color.

        G: `int`
            A band number that will render the green color.

        B: `int`
            A band number that will render the blue color.

        suffix: `string [default None]`
          Add a suffix to the file name.
    """
    img = _linear_stretch(M, R, G, B)
    plt.ioff()
    if suffix == None:
        fout = osp.join(path, 'linear_stretch.png')
    else:
        fout = osp.join(path, 'linear_stretch_{0}.png'.format(suffix))
    plt.imsave(fout, img)
    plt.close()
项目:AdversarialMachineLearning_COMP551    作者:arunrawlani    | 项目源码 | 文件源码
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
        """

    # 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:
        print('HAHHAHAHAHHAHAHAHAHAHAHHAHAHAHHAHAHA')
                plt.imshow(data[x, y, :, :, 0], cmap='gray')
            else:
                plt.imshow(data[x, y, :, :, :])

    # Draw the plot and return
    plt.savefig("grid_cifar")
    return figure

#getting CIFAR10 dataset and preprocessing it
项目:AdversarialMachineLearning_COMP551    作者:arunrawlani    | 项目源码 | 文件源码
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
        """

    # 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.savefig("grid_cifar")
    return figure

#getting CIFAR10 dataset and preprocessing it
项目:synchrony    作者:cknd    | 项目源码 | 文件源码
def createanim(data,start,skip,title=None,cmap='bone', ms_per_step=None):
    """
    Return an animation of a single simulation run, each node
    represented (via its node label) as pixel (i,j) in an MxN image.
    So this will only be useful for grid graphs.

    Args:
        data: MxNxT array of voltage traces
        start: first timestep to show
        skip: timesteps to advance in each frame (higher -> faster)
        title: figure title
        cmap: matplotlib colormap (name OR object)

    Return:
        matplotlib animation object
    """
    plt.ioff()
    fig = plt.figure(figsize=fig_size)
    titlefont = {'color'  : 'black', 'size':12}
    ax  = plt.axes()#(xlim=(0, data.shape[1]), ylim=(data.shape[0]))
    picture = ax.imshow(data[:, :, start], vmin=data.min(), vmax=data.max(),
                         interpolation="nearest", cmap=cmap)
    plt.colorbar(picture,ax=ax,shrink=0.7)
    def init():
        picture.set_data(data[:,:,start])
        return picture

    def animate(i):
        printprogress("animating frame",start+i*skip,data.shape[2])
        if i*skip < data.shape[2]:
            picture.set_data(data[:,:,start+i*skip])

            t = " {}ms".format(start+i*skip * ms_per_step) if ms_per_step is not None else ""
            plt.title(title+t,titlefont)
        return picture
    anim = animation.FuncAnimation(fig, animate, init_func=init,
                                          frames=(data.shape[2]-start)/skip,interval=1, blit=False)
    return anim
项目:mrflow    作者:jswulff    | 项目源码 | 文件源码
def plot_scatter(pt, title, I=None,masks=None, outpath='.'):
    if plt is None:
        return
    plt.ioff()
    if masks is None:
        masks = [np.ones(pt.shape[0])>0,]
    colors = ['r','b','g','c','y']
    plt.figure()
    if I is not None:
        plt.imshow(I)
    for i,m in enumerate(masks):
        plt.plot(pt[m,0],
                pt[m,1],
                '.{}'.format(colors[i%len(colors)]))

    if I is not None:
        ymax = I.shape[0]
        xmax = I.shape[1]
    else:
        ymax = pt[:,1].max()
        xmax = pt[:,0].max()
        plt.axis('equal')
    plt.title(title)
    plt.ylim([ymax,0])
    plt.xlim([0,xmax])
    save_figure(title, outpath)