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


Python pylab.subplot函数代码示例

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


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

示例1: plot_tracks

def plot_tracks(src, fakewcs, spa=None, **kwargs):
    # NOTE -- MAGIC 61 = monthly; this is ASSUMEd below.
    tt = np.linspace(2010., 2015., 61)
    t0 = TAITime(None, mjd=TAITime.mjd2k + 365.25*10)
    #rd0 = src.getPositionAtTime(t0)
    #print 'rd0:', rd0
    xx,yy = [],[]
    rr,dd = [],[]
    for t in tt:
        #print 'Time', t
        rd = src.getPositionAtTime(t0 + (t - 2010.)*365.25*24.*3600.)
        ra,dec = rd.ra, rd.dec
        rr.append(ra)
        dd.append(dec)
        ok,x,y = fakewcs.radec2pixelxy(ra,dec)
        xx.append(x - 1.)
        yy.append(y - 1.)

    if spa is None:
        spa = [None,None,None]
    for rows,cols,sub in spa:
        if sub is not None:
            plt.subplot(rows,cols,sub)
        ax = plt.axis()
        plt.plot(xx, yy, 'k-', **kwargs)
        plt.axis(ax)

    return rr,dd,tt
开发者ID:eddienko,项目名称:tractor,代码行数:28,代码来源:rogue.py

示例2: plot_vm

 def plot_vm(self):
     """Plot Vm for presynaptic compartment and soma - along with
     the same in NEURON simulation if possible."""
     pylab.subplot(211)
     pylab.title('Soma Vm')
     pylab.plot(self.tseries*1e3, self.somaVmTab.vec * 1e3,
                label='Vm (mV) - moose')
     pylab.plot(self.tseries*1e3, self.injectionTab.vec * 1e9,
                label='Stimulus (nA)')
     try:
         nrn_data = np.loadtxt('../nrn/data/%s_soma_Vm.dat' % \
                                   (self.celltype))
         nrn_indices = np.nonzero(nrn_data[:, 0] <= self.tseries[-1]*1e3)[0]                        
         pylab.plot(nrn_data[nrn_indices,0], nrn_data[nrn_indices,1], 
                    label='Vm (mV) - neuron')
     except IOError:
         print 'No neuron data found.'
     pylab.legend()
     pylab.subplot(212)
     pylab.title('Presynaptic Vm')
     pylab.plot(self.tseries*1e3, self.presynVmTab.vec * 1e3,
                label='Vm (mV) - moose')
     pylab.plot(self.tseries*1e3, self.injectionTab.vec * 1e9,
                label='Stimulus (nA)')
     try:
         nrn_data = np.loadtxt('../nrn/data/%s_presynaptic_Vm.dat' % \
                                   (self.celltype))
         nrn_indices = np.nonzero(nrn_data[:, 0] <= self.tseries[-1]*1e3)[0]
         pylab.plot(nrn_data[nrn_indices,0], nrn_data[nrn_indices,1], 
                    label='Vm (mV) - neuron')
     except IOError:
         print 'No neuron data found.'
     pylab.legend()
     pylab.show()
开发者ID:Vivek-sagar,项目名称:moose-1,代码行数:34,代码来源:cell_test_util.py

示例3: Xtest2

    def Xtest2(self):
        """
        Test from Kate Marvel
        As the following code snippet demonstrates, regridding a
        cdms2.tvariable.TransientVariable instance using regridTool='regrid2' 
        results in a new array that is masked everywhere.  regridTool='esmf' 
        and regridTool='libcf' both work as expected.

        This passes.
        """
        import cdms2 as cdms
        import numpy as np

        filename = cdat_info.get_sampledata_path() + '/clt.nc'
        a=cdms.open(filename)
        data=a('clt')[0,...]

        print data.mask #verify this data is not masked

        GRID= data.getGrid() # input = output grid, passes

        test_data=data.regrid(GRID,regridTool='regrid2')

        # check that the mask does not extend everywhere...
        self.assertNotEqual(test_data.mask.sum(), test_data.size)
        
        if PLOT:
            pylab.subplot(2, 1, 1)
            pylab.pcolor(data[...])
            pylab.title('data')
            pylab.subplot(2, 1, 2)
            pylab.pcolor(test_data[...])
            pylab.title('test_data (interpolated data)')
            pylab.show()
开发者ID:UV-CDAT,项目名称:uvcdat,代码行数:34,代码来源:testMarvel.py

示例4: trace

def trace(data, name, format='png', datarange=(None, None), suffix='', path='./', rows=1, columns=1, 
    num=1, last=True, fontmap = None, verbose=1):
    """
    Generates trace plot from an array of data.

    :Arguments:
        data: array or list
            Usually a trace from an MCMC sample.

        name: string
            The name of the trace.
            
        datarange: tuple or list
            Preferred y-range of trace (defaults to (None,None)).

        format (optional): string
            Graphic output format (defaults to png).

        suffix (optional): string
            Filename suffix.

        path (optional): string
            Specifies location for saving plots (defaults to local directory).
            
        fontmap (optional): dict
            Font map for plot.

    """

    if fontmap is None: fontmap = {1:10, 2:8, 3:6, 4:5, 5:4}

    # Stand-alone plot or subplot?
    standalone = rows==1 and columns==1 and num==1

    if standalone:
        if verbose>0:
            print_('Plotting', name)
        figure()

    subplot(rows, columns, num)
    pyplot(data.tolist())
    ylim(datarange)

    # Plot options
    title('\n\n   %s trace'%name, x=0., y=1., ha='left', va='top', fontsize='small')

    # Smaller tick labels
    tlabels = gca().get_xticklabels()
    setp(tlabels, 'fontsize', fontmap[rows/2])

    tlabels = gca().get_yticklabels()
    setp(tlabels, 'fontsize', fontmap[rows/2])

    if standalone:
        if not os.path.exists(path):
            os.mkdir(path)
        if not path.endswith('/'):
            path += '/'
        # Save to file
        savefig("%s%s%s.%s" % (path, name, suffix, format))
开发者ID:CosmologyTaskForce,项目名称:pymc,代码行数:60,代码来源:Matplot.py

示例5: plot_Barycenter

def plot_Barycenter(dataset_name, feat, unfeat, repo):

    if dataset_name==MNIST:
        _, _, test=get_data(dataset_name, repo, labels=True)
        xtest1,_,_, labels,_=test
    else:
        _, _, test=get_data(dataset_name, repo, labels=False)
        xtest1,_,_ =test
        labels=np.zeros((len(xtest1),))
    # get labels
    def bary_wdl2(index): return _bary_wdl2(index, xtest1, feat, unfeat)
    
    n=xtest1.shape[-1]
    
    num_class = (int)(max(labels)+1)
    barys=[bary_wdl2(np.where(labels==i)) for i in range(num_class)]
    pl.figure(1, (num_class, 1))
    for i in range(num_class):
        pl.subplot(1,10,1+i)
        pl.imshow(barys[i][0,0,:,:],cmap='Blues',interpolation='nearest')
        pl.xticks(())
        pl.yticks(())
        if i==0:
            pl.ylabel('DWE Bary.')
        if num_class >1:
            pl.title('{}'.format(i))
    pl.tight_layout(pad=0,h_pad=-2,w_pad=-2) 
    pl.savefig("imgs/{}_dwe_bary.pdf".format(dataset_name))
开发者ID:RobinROAR,项目名称:TensorflowTutorialsCode,代码行数:28,代码来源:test_model.py

示例6: graphError

            def graphError(predictedPercentChanges, actualPercentChanges, title):
                # considering error and only considering it as error when the signs are different

                def computeSignedError(pred, actual):

                    if (pred > 0 and actual > 0) or (pred < 0 and actual < 0):
                        return 0

                    else:
                        error = abs(pred - actual)
                        # print 'pred: {0}, actual: {1}, error: {2}'.format(pred, actual, error)
                        return error

                signedError = map(
                    lambda pred, actual: computeSignedError(pred, actual), predictedPercentChanges, actualPercentChanges
                )
                pl.figure(2)
                pl.title(title + " Error")
                pl.subplot(211)
                pl.plot(signedError)
                pl.xlabel("Time step")
                pl.ylabel("Error (0 if signs are same and normal error if signs are different)")

                pl.figure(3)
                pl.title(title + " Actual vs Predictions")
                pl.subplot(211)
                pl.plot(
                    range(len(predictedPercentChanges)),
                    predictedPercentChanges,
                    "ro",
                    range(len(actualPercentChanges)),
                    actualPercentChanges,
                    "bs",
                )
开发者ID:xeddmc,项目名称:AI-bitcoin,代码行数:34,代码来源:NeuralNetwork.py

示例7: T2_cpmg_process

def T2_cpmg_process(folder_to_process,plot='y'):
    """Given a folder of images will process cpmg data and return
    fitted T2 values and associated uncertainties"""
    data=img_roi_signal([folder_to_process],['EchoTime'])
    rois=data[0][0]
    TEs=data[2][0]
    mean_signal_mat=data[3]
    serr_signal_mat=data[4]
        
    if plot=='y':
        plt.figure()
    spin_echo_fits=[]
    for jj in np.arange(len(rois)-2):
        mean_sig=mean_signal_mat[0,jj,:]
        #serr_sig=serr_signal_mat[0,jj,:]
        mean_noise=np.mean(mean_signal_mat[0,-2,:])
        try:
            spin_echo_fit = SE_fit_new( np.array(TEs[0:]), mean_sig[0:], mean_noise, 'n' )
            if plot=='y':
                TE_full=np.arange(0,400,1)
                plt.subplot(4,4,jj+1)
                plt.plot(np.array(TEs[0:]), mean_sig[0:],'o')
                plt.plot(TE_full,spin_echo_fit(TE_full))
            
            spin_echo_fits.append(spin_echo_fit)
        except RuntimeError: 
            print 'RuntimeError'
            spin_echo=fitting.model('M0*exp(-x/T2)+a',{'M0':0,'T2':0,'a':0}) 
            spin_echo_fits.append(spin_echo)
    return spin_echo_fits   
开发者ID:JoshBradshaw,项目名称:bloodtools,代码行数:30,代码来源:blood_tools.py

示例8: main

def main():
    star = StarBinary(90.0, 0.5, nside=64, limb_law=-1, limb_coeff=[0.8])
    Flux0 = star.flux(0.0)
    phases = np.linspace(-0.5, 0.5, 100)

    flux1 = np.zeros(len(phases))
    for i in range(len(phases)):
        flux1[i] = star.flux(phases[i]) / Flux0

    # for tt in np.arange(0,360,80):
    # star.makeSpot(0,-45,10.,0.8)
    # star.makeSpot(45,+00,10.,0.8)
    # star.makeSpot(00, -90, 20., 0.)
    # for theta in range(0,360,45):
    #	star.makeSpot(theta,65,10.,0.8)

    # star.makeSpot(00,-90,20.,0.)
    # star.makeSpot(0,+45,10.,0.8)
    # star.makeSpot(270,-10.,10.,0.8)
    # star.makeSpot(180,-45.,10.,0.8)
    #	star.makeSpot(tt,65.,10.,0.5)

    flux2 = np.zeros(len(phases))
    for i in range(len(phases)):
        flux2[i] = star.flux(phases[i]) / Flux0

    H.mollview(star.I, sub=211, rot=(-90, 90))

    #ff = np.loadtxt('/tmp/cl.dat', unpack=True)

    py.subplot(212)
    py.plot(phases, flux1, '-')
    # py.plot(phases,flux2,'-')
    #py.plot(ff[0], ff[1], '.')
    py.show()
开发者ID:tribeiro,项目名称:starmod,代码行数:35,代码来源:testFlux_02.py

示例9: sim_results

def sim_results(obs, modes, stars, model, data):


    synth = model.generate_data(modes)
    synth_stats = model.summary_stats(synth)
    obs_stats = model.summary_stats(obs)


    f = plt.figure(figsize=(15,3))
    plt.suptitle('Obs Cand.:{}; Sim Cand.:{}'.format(obs.size, synth.size))
    plt.rc('legend', fontsize='xx-small', frameon=False)
    plt.subplot(121)
    bins = opt_bin(obs_stats[0],synth_stats[0])
    plt.hist(obs_stats[0], bins=bins, histtype='step', label='Data', lw=2)
    plt.hist(synth_stats[0], bins=bins, histtype='step', label='Simulation', lw=2)
    plt.xlabel(r'$\xi$')
    plt.legend()

    plt.subplot(122)
    bins = opt_bin(obs_stats[1],synth_stats[1])
    plt.hist(obs_stats[1], bins=np.arange(bins.min()-0.5, bins.max()+1.5,
                                          1),
             histtype='step', label='Data', log=True, lw=2)
    plt.hist(synth_stats[1], bins=np.arange(bins.min()-0.5, bins.max()+1.5,
                                            1),
             histtype='step', label='Simulation', log=True, lw=2)
    plt.xlabel(r'$N_p$')
    plt.legend()
开发者ID:rcmorehead,项目名称:simplanets,代码行数:28,代码来源:abcplot.py

示例10: graphSimpleResults

def graphSimpleResults(resultsDir):
    x=[]
    y=[]
    files=[open("%s/objectiveFunctionReport.txt" % resultsDir),
       open("%s/fitnessReport.txt" % resultsDir)]
    for f in files:
        x.append([])
        y.append([])
        i=len(x)-1
        for line in f:
            line=line.split(',')
            if line[0] != "gen":
                x[i].append(int(line[0]))
                y[i].append(float(line[1]))

    ylen=len(y[0])
    pl.subplot(2,1,1)
    pl.plot(x[0],y[0],'bo')
    pl.ylabel('Maximum x')
    pl.title('Maximizing x**2 with SGA')
    pl.annotate("{0:,}".format(y[0][0]),xy=(x[0][0],y[0][0]),  xycoords='data',
             xytext=(50, 30), textcoords='offset points',
             arrowprops=dict(arrowstyle="->") )
    pl.annotate("{0:,}".format(y[0][ylen-1]),xy=(x[0][ylen-1],y[0][ylen-1]),  xycoords='data',
             xytext=(-30, -30), textcoords='offset points',
             arrowprops=dict(arrowstyle="->") )

    pl.subplot(2,1,2)
    pl.plot(x[1],y[1],'go')
    pl.xlabel('Generation')
    pl.ylabel('Fitness')
    pl.savefig("%s/simple_result.png" % resultsDir)
开发者ID:valreee,项目名称:GeneticAlgorithms,代码行数:32,代码来源:utilities.py

示例11: graphTSPResults

def graphTSPResults(resultsDir,numberOfTours):
    x=[]
    y=[]
    files=[open("%s/objectiveFunctionReport.txt" % resultsDir),
       open("%s/fitnessReport.txt" % resultsDir)]
    for f in files:
        x.append([])
        y.append([])
        i=len(x)-1
        for line in f:
            line=line.split(',')
            if line[0] != "gen":
                x[i].append(int(line[0]))
                y[i].append(float(line[1] if i==1 else line[2]))
            
    ylen=len(y[0])
    pl.subplot(2,1,1)
    pl.plot(x[0],y[0],'bo')
    pl.ylabel('Minimum Distance')
    pl.title("TSP with a %s City Tour" % numberOfTours)
    pl.annotate("{0:,}".format(y[0][0]),xy=(x[0][0],y[0][0]),  xycoords='data',
             xytext=(30, -30), textcoords='offset points',
             arrowprops=dict(arrowstyle="->") )
    pl.annotate("{0:,}".format(y[0][ylen-1]),xy=(x[0][ylen-1],y[0][ylen-1]),  xycoords='data',
             xytext=(-30,30), textcoords='offset points',
             arrowprops=dict(arrowstyle="->") )

    pl.subplot(2,1,2)
    pl.plot(x[1],y[1],'go')
    pl.xlabel('Generation')
    pl.ylabel('Fitness')
    pl.savefig("%s/tsp_result.png" % resultsDir)
    pl.clf()
开发者ID:valreee,项目名称:GeneticAlgorithms,代码行数:33,代码来源:utilities.py

示例12: main

def main():
    src_cv_img_1 = cv.LoadImage("data/gorskaya/images/1/g126.jpg")
    src_cv_img_gray_1 = cv.LoadImage("data/gorskaya/images/1/g126.jpg", 
        cv.CV_LOAD_IMAGE_GRAYSCALE)

    src_cv_img_2 = cv.LoadImage("data/gorskaya/images/1/g127.jpg")
    src_cv_img_gray_2 = cv.LoadImage("data/gorskaya/images/1/g127.jpg", 
        cv.CV_LOAD_IMAGE_GRAYSCALE)

    (keypoints_1, descriptors_1) = \
        cv.ExtractSURF(src_cv_img_gray_1, None, cv.CreateMemStorage(), 
            (0, 30000, 3, 1))
    (keypoints_2, descriptors_2) = \
        cv.ExtractSURF(src_cv_img_gray_2, None, cv.CreateMemStorage(), 
            (0, 30000, 3, 1))

    print("Found {0} and {1} keypoints".format(
        len(keypoints_1), len(keypoints_2)))

    src_arr_1 = array(src_cv_img_1[:, :])[:, :, ::-1]
    src_arr_2 = array(src_cv_img_2[:, :])[:, :, ::-1]

    pylab.rc('image', interpolation='nearest')

    pylab.subplot(121)
    pylab.imshow(src_arr_1)
    pylab.plot(*zip(*[k[0] for k in keypoints_1]), 
        marker='.', color='r', ls='')

    pylab.subplot(122)
    pylab.imshow(src_arr_2)
    pylab.plot(*zip(*[k[0] for k in keypoints_2]), 
        marker='.', color='r', ls='')

    pylab.show()
开发者ID:rutsky,项目名称:semester09,代码行数:35,代码来源:demo_feature_points.py

示例13: display_coeff

def display_coeff(data=None):
    betaAll,betaErrAll, R2adjAll = measure_stamp_coeff(data = data, zernike_max_order=20)
    ind = np.arange(len(betaAll[0]))
    momname = ('M20','M22.Real','M22.imag','M31.real','M31.imag','M33.real','M33.imag')
    fmtarr = ['bo-','ro-','go-','co-','mo-','yo-','ko-']
    pl.figure(figsize=(17,13))
    for i in range(7):
        pl.subplot(7,1,i+1)
        pl.errorbar(ind,betaAll[i],yerr = betaErrAll[i],fmt=fmtarr[i])
        pl.grid()
        pl.xlim(-1,21)
        if i ==0:
            pl.ylim(-10,65)
        elif i ==1:
            pl.ylim(-5,6)
        elif i ==2:
            pl.ylim(-5,6)
        elif i == 3:
            pl.ylim(-0.1,0.1)
        elif i == 4:
            pl.ylim(-0.1,0.1)
        elif i ==5:
            pl.ylim(-100,100)
        elif i == 6:
            pl.ylim(-100,100)
        pl.xticks(ind,('','','','','','','','','','','','','','','','','','','',''))
        pl.ylabel(momname[i])
    pl.xticks(ind,('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19'))
    pl.xlabel('Zernike Coefficients')
    return '--- done ! ----'
开发者ID:jgbrainstorm,项目名称:des-sv,代码行数:30,代码来源:psfFocus.py

示例14: traceplot

def traceplot(traces, thin, burn):
    '''
    Plot parameter estimates for different levels of the model
    into the same plots. Black lines are individual observers
    and red lines are mean estimates.
    '''
    variables = ['Slope1', 'Slope2', 'Offset', 'Split']
    for i, var in enumerate(variables):
        plt.subplot(2, 2, i + 1)
        vals = get_values(traces, var, thin, burn)
        dim = (vals.min() - vals.std(), vals.max() + vals.std())
        x = plt.linspace(*dim, num=1000)
        for v in vals.T:
            a = gaussian_kde(v)
            y = a.evaluate(x)
            y = y / y.max()
            plt.plot(x, y, 'k', alpha=.5)
        try:
            vals = get_values(traces, 'Mean_' + var, thin, burn)
            a = gaussian_kde(vals)
            y = a.evaluate(x)
            y = y / y.max()
            plt.plot(x, y, 'r', alpha=.75)
        except KeyError:
            pass
        plt.ylim([0, 1.1])
        plt.yticks([0])
        sns.despine(offset=5, trim=True)
        plt.title(var)
开发者ID:nwilming,项目名称:mcmodels,代码行数:29,代码来源:appc.py

示例15: display_orbit

def display_orbit(input, amplitude=0.000001):
    import matplotlib.pyplot
    import pylab

    # Compare the power spectral density functions of the system with and
    #  without the input sequence.
    x = [0.4, 0.6]
    X = []
    for i in range(warmups):
        x = network(x)
        x[0] = x[0] + ( amplitude * input[0][i % len(input[0])] )
        x[1] = x[1] + ( amplitude * input[1][i % len(input[1])] )
    for i in range(measure):
        X.append(x[0])
        x = network(x)
        x[0] = x[0] + ( amplitude * input[0][i % len(input[0])] )
        x[1] = x[1] + ( amplitude * input[1][i % len(input[1])] )
    pylab.subplot(2,1,1)
    matplotlib.pyplot.psd(X,1024,32)

    x = [0.4, 0.6]
    X = []
    for i in range(warmups):
        x = network(x)
        # x[0] = x[0] + ( amplitude * input[i % len(input)] )
    for i in range(measure):
        X.append(x[0])
        x = network(x)
        # x[0] = x[0] + ( amplitude * input[i % len(input)] )
    pylab.subplot(2,1,2)
    matplotlib.pyplot.psd(X,1024,32)

    pylab.show()
开发者ID:ralphbean,项目名称:ms-thesis,代码行数:33,代码来源:misc.py


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