当前位置: 首页>>代码示例>>Python>>正文


Python pylab.tight_layout函数代码示例

本文整理汇总了Python中matplotlib.pylab.tight_layout函数的典型用法代码示例。如果您正苦于以下问题:Python tight_layout函数的具体用法?Python tight_layout怎么用?Python tight_layout使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了tight_layout函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: measure_psf

def measure_psf(vignet, pixscale=1., show=False, mask_value=None):
    y, x = np.mgrid[-vignet.shape[0]/2:vignet.shape[0]/2, -vignet.shape[1]/2:vignet.shape[1]/2]*pixscale
    if mask_value :
        vignet = ma.masked_values(vignet, mask_value).filled(0)
    # Fit the data using astropy.modeling
    p_init=models.Gaussian2D(amplitude=vignet.max(), x_mean=0., y_mean=0.,
        x_stddev=2*pixscale, y_stddev=2*pixscale, theta=0, cov_matrix=None)
    fit_p = fitting.LevMarLSQFitter()

    p = fit_p(p_init, x, y, vignet)
    barycenter=measure_barycenter(vignet, pixscale=pixscale)
    
    # Plot the data with the best-fit model
    P.figure(figsize=(8, 2.5))
    P.subplot(1, 3, 1)
    P.imshow(vignet, origin='lower', interpolation='nearest', vmin=vignet.min(), vmax=vignet.max())
    P.title("Data")
    P.subplot(1, 3, 2)
    P.imshow(p(x, y), origin='lower', interpolation='nearest', vmin=vignet.min(), vmax=vignet.max())
    P.scatter(vignet.shape[0]/2, vignet.shape[1]/2,marker="+")
    P.annotate("({:.3f},{:.3f})".format(*barycenter), (vignet.shape[0]/3, vignet.shape[1]/3))
    P.title("Model - psf = {:.2f}".format(2.3548*np.mean([p.x_stddev.value, p.y_stddev.value])))
    P.subplot(1, 3, 3)
    P.imshow(vignet - p(x, y), origin='lower', interpolation='nearest', vmin=-vignet.max()/10,vmax=vignet.max()/10)
    P.title("Residual")
    P.tight_layout()
    if show :
        P.show()
    
    return p
开发者ID:rfahed,项目名称:extProcess,代码行数:30,代码来源:image.py

示例2: plot_graph

    def plot_graph(self):
        '''
        plots a matplotlib graph from the stocks data. Dates on the x axis and
        Closing Prices on the y axis. Then adds it to the graph_win in the
        display frame as a tk widget()
        '''
        x_axis = [
			dt.datetime.strptime(self.daily_data[day][0], '%Y-%m-%d')
            for day in range(1, len(self.daily_data) - 1)
		]
        y_axis = [
			self.daily_data[cls_adj][-1]
            for cls_adj in range(1, len(self.daily_data) - 1)
		]
        fig = plt.figure()
        ax = fig.add_subplot("111")
        ax.plot(
			x_axis,
            y_axis,
            marker='h',
            linestyle='-.',
            color='r',
            label='Daily Adjusted Closing Prices'
		)
        labels = ax.get_xticklabels()
        for label in labels:
            label.set_rotation(15)
        plt.xlabel('Dates')
        plt.ylabel('Close Adj')
        plt.legend()
        plt.tight_layout()  # adjusts the graph to fit in the space its limited to
        self.data_plot = FigureCanvasTkAgg(fig, master=self.display)
        self.data_plot.show()
        self.graph_win = self.data_plot.get_tk_widget()
开发者ID:FinbarT,项目名称:Stocks-plotter-App,代码行数:34,代码来源:Stocks-plotter-App.py

示例3: plot_corner_posteriors

    def plot_corner_posteriors(self, savefile=None, labels=["T1", "R1", "Av", "T2", "R2"]):
        '''
        Plots the corner plot of the MCMC results.
        '''
        ndim = len(self.sampler.flatchain[0,:])
        chain = self.sampler
        samples = chain.flatchain
        
        samples = samples[:,0:ndim]  
        plt.figure(figsize=(8,8))
        fig = corner.corner(samples, labels=labels[0:ndim])
        plt.title("MJD: %.2f"%self.mjd)
        name = self._get_save_path(savefile, "mcmc_posteriors")
        plt.savefig(name)
        plt.close("all")
        

        plt.figure(figsize=(8,ndim*3))
        for n in range(ndim):
            plt.subplot(ndim,1,n+1)
            chain = self.sampler.chain[:,:,n]
            nwalk, nit = chain.shape
            
            for i in np.arange(nwalk):
                plt.plot(chain[i], lw=0.1)
                plt.ylabel(labels[n])
                plt.xlabel("Iteration")
        name_walkers = self._get_save_path(savefile, "mcmc_walkers")
        plt.tight_layout()
        plt.savefig(name_walkers)
        plt.close("all")  
开发者ID:nblago,项目名称:utils,代码行数:31,代码来源:BBFit.py

示例4: plot

    def plot(self,file):
        cds = CaseDataset(file, 'bson')
        data = cds.data.driver('driver').by_variable().fetch()
        cds2 = CaseDataset('../output/therm_mc_20141110173851.bson', 'bson')
        data2 = cds2.data.driver('driver').by_variable().fetch()
        
        #temp
        temp_boundary_k = data['hyperloop.temp_boundary']
        temp_boundary_k.extend(data2['hyperloop.temp_boundary'])
        temp_boundary = [((x-273.15)*1.8 + 32) for x in temp_boundary_k]
        #histogram
        n, bins, patches = plt.hist(temp_boundary, 100, normed=1, histtype='stepfilled')
        plt.setp(patches, 'facecolor', 'b', 'alpha', 0.75)

        #stats
        mean = np.average(temp_boundary)
        std = np.std(temp_boundary)
        percentile = np.percentile(temp_boundary,99.5)
        print "mean: ", mean, " std: ", std, " 99.5percentile: ", percentile
        x = np.linspace(50,170,150)
        plt.plot(x,mlab.normpdf(x,mean,std), color='black', lw=2)
        plt.xlim([60,160])
        plt.ylabel('Probability', fontsize=18)
        plt.xlabel(u'Equilibrium Temperature, \N{DEGREE SIGN}F', fontsize=18)
        #plt.show()
        plt.tight_layout()
        plt.savefig('../output/histo.pdf', dpi=300)
开发者ID:jcchin,项目名称:Hyperloop,代码行数:27,代码来源:mc_histo.py

示例5: plot_abc

    def plot_abc(self, uarg, param):
        """Plot a() and b() functions on the same plot.

        """
        plt.figure(figsize=(8, 4))

        plt.subplot(1, 3, 1)
        plt.plot(uarg, self.afun(uarg, param))
        plt.axhline(0)
        plt.axvline(0)
        plt.ylabel('$a(u)$')
        plt.xlabel('$u$')

        plt.subplot(1, 3, 2)
        plt.plot(uarg, self.bfun(uarg, param))
        plt.axhline(0)
        plt.axvline(0)
        plt.ylabel('$b(u)$')
        plt.xlabel('$u$')

        plt.subplot(1, 3, 3)
        plt.plot(uarg, self.cfun(uarg, param))
        plt.axhline(0)
        plt.axvline(0)
        plt.ylabel('$c(u)$')
        plt.xlabel('$u$')

        plt.tight_layout()
        plt.show()
开发者ID:khrapovs,项目名称:argamma,代码行数:29,代码来源:arg.py

示例6: zsview

def zsview(im, cmap=pl.cm.gray, figsize=(8,5), contours=False, ccolor='r'):
    z1, z2 = zscale(im)
    pl.figure(figsize=figsize)
    pl.imshow(im, vmin=z1, vmax=z2, origin='lower', cmap=cmap, interpolation='none')
    if contours:
        pl.contour(im, levels=[z2], origin='lower', colors=ccolor)
    pl.tight_layout()
开发者ID:cenko,项目名称:RATIR-GSFC,代码行数:7,代码来源:astro_functs.py

示例7: save

    def save(self, out_path):
        '''Saves a figure for the monitor
        
        Args:
            out_path: str
        '''
        
        plt.clf()
        np.set_printoptions(precision=4)
        font = {
            'size': 7
        }
        matplotlib.rc('font', **font)
        y = 2
        x = ((len(self.d) - 1) // y) + 1
        fig, axes = plt.subplots(y, x)
        fig.set_size_inches(20, 8)

        for j, (k, v) in enumerate(self.d.iteritems()):
            ax = axes[j // x, j % x]
            ax.plot(v, label=k)
            if k in self.d_valid.keys():
                ax.plot(self.d_valid[k], label=k + '(valid)')
            ax.set_title(k)
            ax.legend()

        plt.tight_layout()
        plt.savefig(out_path, facecolor=(1, 1, 1))
        plt.close()
开发者ID:Jeremy-E-Johnson,项目名称:cortex,代码行数:29,代码来源:monitor.py

示例8: run_method_usage

def run_method_usage(methods,cases):
    methods = [m[0] for m in methods]
    # Bootstrap the percentage error bars:
    percents =[]
    for i in range(10000):
        nc = resample(cases)
        percents.append(100*np.sum(nc,axis=0)/len(nc))
    percents=np.array(percents)
    mean_percents = np.mean(percents,axis=0)
    std_percents = np.std(percents,axis=0)*1.96
    inds=np.argsort(mean_percents).tolist()
    inds.reverse()
    avg_usage = np.mean(mean_percents)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    x=np.arange(len(methods))
    ax.plot(x,[avg_usage]*len(methods),'-',color='0.25',lw=1,alpha=0.2)
    ax.bar(x, mean_percents[inds], 0.6, color=paired[0],linewidth=0,
           yerr=std_percents[inds],ecolor=paired[1])
    #ax.set_title('Method Occurrence')
    ax.set_ylabel('Occurrence %',fontsize=30)
    ax.set_xlabel('Method',fontsize=30)
    ax.set_xticks(np.arange(len(methods)))
    ax.set_xticklabels(np.array(methods)[inds],fontsize=8)
    fig.autofmt_xdate()
    fix_axes()
    plt.tight_layout()
    fig.savefig(figure_path+'method_occurrence.pdf', bbox_inches=0)
    fig.show()
    return inds,mean_percents[inds]
开发者ID:IDEALLab,项目名称:design_method_recommendation_JMD_2014,代码行数:30,代码来源:paper_experiments.py

示例9: plot

def plot(rho, u, uLB, tau, rho_history, zdjecia, image, nx, maxIter ):
#    plt.figure(figsize=(15,15))
#    plt.subplot(4, 1, 1)
#    plt.imshow(u[1,:,0:50],vmin=-uLB*.15, vmax=uLB*.15, interpolation='none')#,cmap=cm.seismic
#    plt.colorbar()
    plt.rcParams["figure.figsize"] = (15,15)
    plt.subplot(5, 1, 1)
    plt.imshow(sqrt(u[0]**2+u[1]**2),vmin=0, vmax=uLB*1.6)#,cmap=cm.seismic
    plt.colorbar()
    plt.title('tau = {:f}'.format(tau))      
    
    plt.subplot(5, 1, 2)
    plt.imshow(u[0,:,:30],  interpolation='none')#,cmap=cm.seismicvmax=uLB*1.6,
    plt.colorbar()
    plt.title('tau = {:f}'.format(tau))  
    
    plt.subplot(5, 1, 3)
    plt.imshow(rho, interpolation='none' )#,cmap=cm.seismic
    plt.title('rho')   
    
    plt.subplot(5, 1,4)
    plt.title(' history rho')
    plt.plot(linspace(0,len(rho_history),len(rho_history)),rho_history)
    plt.xlim([0,maxIter])   
    
    plt.subplot(5, 1,5)
    plt.title(' u0 middle develop')
    plt.plot(linspace(0,nx,len(u[0,20,:])), u[1,20,:])
    plt.tight_layout()                  
    
    plt.savefig(path.join(zdjecia,'f{0:06d}.png'.format(image)))
    plt.clf();
        
开发者ID:ricevind,项目名称:LB_core,代码行数:32,代码来源:symplot.py

示例10: do_plot_extras

    def do_plot_extras(self, extra):
        """ Plot other observed quantities as a function of time.

        Parameters
        ----------
        extra: string
          One of the quantities available in system.extras
        """
        # import pyqtgraph as pg

        colors = 'bgrcmykw' # lets hope for less than 9 data-sets
        t = self.time

        # handle inexistent field
        if extra not in self.extras._fields:
          from shell_colors import red
          msg = red('ERROR: ') + 'The name "%s" is not available in extras.\n' % extra
          clogger.fatal(msg)
          return

        i = self.extras._fields.index(extra) # index corresponding to this quantity

        plt.figure()
        # p = pg.plot()
        plt.plot(t, self.extras[i], 'o', label=extra)
        
        plt.xlabel('Time [days]')
        plt.ylabel(extra + ' []')
        plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05))
        plt.minorticks_on()
        plt.tight_layout()
        plt.show()
开发者ID:sousasag,项目名称:OPEN,代码行数:32,代码来源:classes.py

示例11: _plot

    def _plot(self, doFAP=None):
      """
        Create a plot.
      """
      xlabel = 'Period [d]'
      ylabel = 'Power'

      self.fig = plt.figure()
      self.ax = self.fig.add_subplot(1,1,1)
      self.ax.set_title("Normalized periodogram")
      self.ax.set_xlabel(xlabel)
      self.ax.set_ylabel(ylabel)
      self.ax.semilogx(1./self.freq, self.power, 'b-')
      # plot FAPs
      if doFAP is None: 
        pass
      elif doFAP is True: # do default FAPs of 10%, 1% and 0.1%
        pmin = 1./self.freq.min()
        pmax = 1./self.freq.max()
        plvl1 = self.powerLevel(0.1) # 10% FAP
        plvl2 = self.powerLevel(0.01) # 1% FAP
        plvl3 = self.powerLevel(0.001) # 0.1% FAP
        self.ax.semilogx([pmin, pmax],[plvl1, plvl1],'k-')
        self.ax.semilogx([pmin, pmax],[plvl2, plvl2],'k--')
        self.ax.semilogx([pmin, pmax],[plvl3, plvl3],'k:')

      plt.tight_layout()
      plt.show()
开发者ID:sousasag,项目名称:OPEN,代码行数:28,代码来源:classes.py

示例12: do_plot_obs

    def do_plot_obs(self):
        """ Plot the observed radial velocities as a function of time.
        Data from each file are color coded and labeled.
        """
        # import pyqtgraph as pg

        colors = 'bgrcmykw' # lets hope for less than 9 data-sets
        t, rv, err = self.time, self.vrad, self.error # temporaries
        
        plt.figure()
        # p = pg.plot()
        # plot each files' values
        for i, (fname, [n, nout]) in enumerate(sorted(self.provenance.iteritems())):
            m = n-nout # how many values are there after restriction
            
            # e = pg.ErrorBarItem(x=t[:m], y=rv[:m], \
            #                     height=err[:m], beam=0.5,\
            #                     pen=pg.mkPen(None))
                                # pen={'color': 0.8, 'width': 2})
            # p.addItem(e)
            # p.plot(t[:m], rv[:m], symbol='o')
            plt.errorbar(t[:m], rv[:m], yerr=err[:m], \
                         fmt='o'+colors[i], label=fname)
            t, rv, err = t[m:], rv[m:], err[m:]
        
        plt.xlabel('Time [days]')
        plt.ylabel('RV [km/s]')
        plt.legend()
        plt.tight_layout()
        plt.show()
开发者ID:sousasag,项目名称:OPEN,代码行数:30,代码来源:classes.py

示例13: save

    def save(self, plot_filename, max_col=2):
        fig = plt.figure()
        fig.suptitle(self.title, fontsize=8)

        if len(self.datastore) <= max_col:
            colsz = len(self.datastore)
            rowsz = 1
            for i, d in enumerate(self.datastore):
                if len(d) == 0:
                    continue  # empty space
                ax = fig.add_subplot(rowsz, colsz, i + 1)
                self._plot(i, ax)
        else:
            sz = len(self.datastore)
            colsz = max_col
            rowsz = sz / max_col
            rowsz = rowsz if sz % max_col == 0 else rowsz + 1
            for i, d in enumerate(self.datastore):
                if len(d) == 0:
                    continue  # empty space
                ax = fig.add_subplot(rowsz, colsz, i + 1)
                self._plot(i, ax)

        #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
        plt.tight_layout()
        plt.savefig(plot_filename)

        return self
开发者ID:chrinide,项目名称:ume,代码行数:28,代码来源:visualize.py

示例14: plot_ss_scatter

def plot_ss_scatter(steadies):
    """ Plot scatter plots of steady states
    """

    def do_scatter(i, j, ax):
        """ Draw single scatter plot
        """
        xs, ys = utils.extract(i, j, steadies)
        ax.scatter(xs, ys)

        ax.set_xlabel(r"$S_%d$" % i)
        ax.set_ylabel(r"$S_%d$" % j)

        cc = utils.get_correlation(xs, ys)
        ax.set_title(r"Corr: $%.2f$" % cc)

    dim = steadies.shape[1]
    fig, axarr = plt.subplots(1, int((dim ** 2 - dim) / 2), figsize=(20, 5))

    axc = 0
    for i in range(dim):
        for j in range(dim):
            if i == j:
                break
            do_scatter(i, j, axarr[axc])
            axc += 1

    plt.suptitle("Correlation overview")

    plt.tight_layout()
    save_figure("images/correlation_scatter.pdf", bbox_inches="tight")
    plt.close()
开发者ID:kpj,项目名称:SDEMotif,代码行数:32,代码来源:plotter.py

示例15: plot_ra

def plot_ra(s1, s2, idxs=None, epsilon=0.25, fig=None):
    """Computes the RA plot of two groups of samples"""

    ## compute log2 values
    l1 = np.log2(s1 + epsilon)
    l2 = np.log2(s2 + epsilon)

    ## compute A and R
    r = l1 - l2
    a = (l1 + l2) * 0.5

    fig = pl.figure() if fig is None else fig
    pl.figure(fig.number)

    if idxs is None:
        pl.plot(a, r, '.k', markersize=2)
    else:
        pl.plot(a[~idxs], r[~idxs], '.k', markersize=2)
        pl.plot(a[idxs], r[idxs], '.r')

    pl.axhline(0, linestyle='--', color='k')

    pl.xlabel('(log2 sample1 + log2 sample2) / 2')
    pl.ylabel('log2 sample1 - log2 sample2')

    pl.tight_layout()
开发者ID:BioinformaticsArchive,项目名称:dgeclust,代码行数:26,代码来源:utils.py


注:本文中的matplotlib.pylab.tight_layout函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。