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


Python pylab.savefig函数代码示例

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


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

示例1: create_pie_chart

    def create_pie_chart(self, snapshot, filename=''):
        """
        Create a pie chart that depicts the distribution of the allocated
        memory for a given `snapshot`. The chart is saved to `filename`.
        """
        try:
            from pylab import figure, title, pie, axes, savefig
            from pylab import sum as pylab_sum
        except ImportError:
            return self.nopylab_msg % ("pie_chart")

        # Don't bother illustrating a pie without pieces.
        if not snapshot.tracked_total:
            return ''

        classlist = []
        sizelist = []
        for k, v in list(snapshot.classes.items()):
            if v['pct'] > 3.0:
                classlist.append(k)
                sizelist.append(v['sum'])
        sizelist.insert(0, snapshot.asizeof_total - pylab_sum(sizelist))
        classlist.insert(0, 'Other')
        #sizelist = [x*0.01 for x in sizelist]

        title("Snapshot (%s) Memory Distribution" % (snapshot.desc))
        figure(figsize=(8, 8))
        axes([0.1, 0.1, 0.8, 0.8])
        pie(sizelist, labels=classlist)
        savefig(filename, dpi=50)

        return self.chart_tag % (self.relative_path(filename))
开发者ID:ppizarror,项目名称:Hero-of-Antair,代码行数:32,代码来源:classtracker_stats.py

示例2: geweke_plot

def geweke_plot(data, name, format='png', suffix='-diagnostic', path='./', fontmap = None, 
    verbose=1):
    # Generate Geweke (1992) diagnostic plots

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

    # Generate new scatter plot
    figure()
    x, y = transpose(data)
    scatter(x.tolist(), y.tolist())

    # Plot options
    xlabel('First iteration', fontsize='x-small')
    ylabel('Z-score for %s' % name, fontsize='x-small')

    # Plot lines at +/- 2 sd from zero
    pyplot((nmin(x), nmax(x)), (2, 2), '--')
    pyplot((nmin(x), nmax(x)), (-2, -2), '--')

    # Set plot bound
    ylim(min(-2.5, nmin(y)), max(2.5, nmax(y)))
    xlim(0, nmax(x))

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

示例3: compareAnimals

def compareAnimals(animals, precision):
    """Assumes animals is a list of animals, precision an int >= 0
       Builds a table of Euclidean distance between each animal"""
    #Get labels for columns and rows
    columnLabels = []
    for a in animals:
        columnLabels.append(a.getName())
    rowLabels = columnLabels[:]
    tableVals = []
    #Get distances between pairs of animals
    #For each row
    for a1 in animals:
        row = []
        #For each column
        for a2 in animals:
            if a1 == a2:
                row.append('--')
            else:
                distance = a1.distance(a2)
                row.append(str(round(distance, precision)))
        tableVals.append(row)
    #Produce table
    table = pylab.table(rowLabels = rowLabels,
                        colLabels = columnLabels,
                        cellText = tableVals,
                        cellLoc = 'center',
                        loc = 'center',
                        colWidths = [0.2]*len(animals))
    table.scale(1, 2.5)
    pylab.axis('off') #Don't display x and y-axes
    pylab.savefig('distances')
开发者ID:Llewelyn62,项目名称:Computational-science,代码行数:31,代码来源:code.py

示例4: simplegrid

def simplegrid():

    nzones = 7

    gr = gpu.grid(nzones, xmin=0, xmax=1)

    gpu.drawGrid(gr, edgeTicks=0)

    # label a few cell-centers
    gpu.labelCenter(gr, nzones/2, r"$i$")
    gpu.labelCenter(gr, nzones/2-1, r"$i-1$")
    gpu.labelCenter(gr, nzones/2+1, r"$i+1$")

    # label a few edges
    gpu.labelEdge(gr, nzones/2, r"$i-1/2$")
    gpu.labelEdge(gr, nzones/2+1, r"$i+1/2$")


    # draw an average quantity
    gpu.drawCellAvg(gr, nzones/2, 0.4, color="r")
    gpu.labelCellAvg(gr, nzones/2, 0.4, r"$\,\langle a \rangle_i$", color="r")

    pylab.axis([gr.xmin-1.5*gr.dx,gr.xmax+1.5*gr.dx, -0.25, 1.5])
    pylab.axis("off")

    pylab.subplots_adjust(left=0.05,right=0.95,bottom=0.05,top=0.95)

    f = pylab.gcf()
    f.set_size_inches(10.0,2.5)


    pylab.savefig("simplegrid2.png")
    pylab.savefig("simplegrid2.eps")
开发者ID:cmsquared,项目名称:numerical_exercises,代码行数:33,代码来源:simplegrid2.py

示例5: plotKerasExperimentcifar10

def plotKerasExperimentcifar10():

    index = 5
    for experiment_number in range(1,index+1):
        outputPath_part_final = os.path.realpath( "/home/jie/docker_folder/random_keras/output_cifar10_mlp/errorFile/hyperopt_experiment_withoutparam_accuracy" + str(experiment_number) + ".txt")
        output_plot = os.path.realpath(
                "/home/jie/docker_folder/random_keras/output_cifar10_mlp/errorFile/plotErrorCurve" + str(experiment_number) + ".pdf")

        df = pd.read_csv(outputPath_part_final,delimiter='\t',header=None)
        df.drop(df.columns[[600]], axis=1, inplace=True)

        i=1
        epochnum = []
        while i<=250:
            epochnum.append(i)
            i = i+1
        i=0
        while i<10:
            df_1=df[df.columns[0:250]].ix[i]
            np.reshape(df_1, (1,250))
            plt.plot(epochnum,df_1)

            i = i+1
        # plt.show()
        # plt.show()
        plt.savefig(output_plot)
        plt.close()
开发者ID:yinyumeng,项目名称:HyperParameterTuning,代码行数:27,代码来源:plotError.py

示例6: plot_sphere_x

def plot_sphere_x( s, fname ):
  """ put plot of ionization fractions from sphere `s` into fname """

  plt.figure()
  s.Edges.units = 'kpc'
  s.r_c.units = 'kpc'
  xx = s.r_c
  L = s.Edges[-1]

  plt.plot( xx, np.log10( s.xHe1 ),
            color='green', ls='-', label = r'$x_{\rm HeI}$' )
  plt.plot( xx, np.log10( s.xHe2 ),
            color='green', ls='--', label = r'$x_{\rm HeII}$' )
  plt.plot( xx, np.log10( s.xHe3 ),
            color='green', ls=':', label = r'$x_{\rm HeIII}$' )

  plt.plot( xx, np.log10( s.xH1 ),
            color='red', ls='-', label = r'$x_{\rm HI}$' )
  plt.plot( xx, np.log10( s.xH2 ),
            color='red', ls='--', label = r'$x_{\rm HII}$' )

  plt.xlim( -L/20, L+L/20 )
  plt.xlabel( 'r_c [kpc]' )

  plt.ylim( -4.5, 0.2 )
  plt.ylabel( 'log 10 ( x )' )

  plt.grid()
  plt.legend(loc='best', ncol=2)
  plt.tight_layout()
  plt.savefig( 'doc/img/x_' + fname )
开发者ID:galtay,项目名称:rabacus,代码行数:31,代码来源:make_doc_images_bgnd_sphere.py

示例7: plotEventFlop

def plotEventFlop(library, num, eventNames, sizes, times, events, filename = None):
  from pylab import legend, plot, savefig, semilogy, show, title, xlabel, ylabel
  import numpy as np

  arches = sizes.keys()
  bs     = events[arches[0]].keys()[0]
  data   = []
  names  = []
  for event, color in zip(eventNames, ['b', 'g', 'r', 'y']):
    for arch, style in zip(arches, ['-', ':']):
      if event in events[arch][bs]:
        names.append(arch+'-'+str(bs)+' '+event)
        data.append(sizes[arch][bs])
        data.append(1e-3*np.array(events[arch][bs][event])[:,1])
        data.append(color+style)
      else:
        print 'Could not find %s in %s-%d events' % (event, arch, bs)
  semilogy(*data)
  title('Performance on '+library+' Example '+str(num))
  xlabel('Number of Dof')
  ylabel('Computation Rate (GF/s)')
  legend(names, 'upper left', shadow = True)
  if filename is None:
    show()
  else:
    savefig(filename)
  return
开发者ID:Kun-Qu,项目名称:petsc,代码行数:27,代码来源:benchmarkExample.py

示例8: manhattonPlot

def manhattonPlot(phenotype_ID, pvalues_lm, ouFprefix, pos, chromBounds):
    for ip, p_ID in enumerate(phenotype_ID):
        pl.figure(figsize=[12,4])
        plot_manhattan(posCum=pos['pos_cum'],pv=pvalues_lm[p_ID].values,chromBounds=chromBounds,thr_plotting=0.05)
        pl.title(p_ID)
        pl.savefig(ouFprefix + '.' + p_ID + '.pdf')
        pl.close('all')
开发者ID:chw333,项目名称:StanfordSGTC,代码行数:7,代码来源:SingleTraitLM.py

示例9: draw

def draw(inF):
    G = nx.Graph()

    inFile = open(inF)
    S = set()
    for line in inFile:
        line = line.strip()
        fields = line.split('\t')
        for item in fields:
            S.add(item)
    inFile.close()

    L = list(S)
    G.add_nodes_from(L)

    LC = []
    for x in L:
        if x == 'EGR1' or x == 'RBM20':
            LC.append('r')
        else:
            LC.append('w')

    inFile = open(inF)
    for line in inFile:
        line = line.strip()
        fields = line.split('\t')
        for i in range(len(fields)-1):
            G.add_edge(fields[i], fields[i+1])
    inFile.close()
    nx.draw_networkx(G,pos=nx.spring_layout(G), node_size=800, font_size=6, node_color=LC)
    limits=plt.axis('off')
    plt.savefig(inF + '.pdf')
开发者ID:chw333,项目名称:StanfordSGTC,代码行数:32,代码来源:03-network-draw.py

示例10: bar_plot_raw

def bar_plot_raw(inF):
    ouF = inF + '.pdf'
    X = []
    Y = []
    inFile = open(inF)
    for line in inFile:
        line = line.strip()
        fields = line.split('\t')
        X.append(int(fields[0]))
        #Y.append(math.log(int(fields[1])+1,2))
        Y.append(int(fields[1]))
    fig = pl.figure()
    N = len(X)
    ax = fig.add_subplot(111)
    ax.set_xlim(0,N + 1)
    ax.set_xticks(range(0,N+2))
    ax.set_xticklabels([0,1] + ['']*(N-1) + [max(X)])
    ax.bar(range(1,N+1), Y, align='center')
    ax.set_xlabel('Start position in the protein')
    ax.set_ylabel('Number of peptides')
    pl.setp(ax.get_xticklines(),visible=False)
    pl.setp(ax.get_xticklabels(),fontsize=6)
    ax.get_children()[2].set_color('g')
    ax.get_children()[3].set_color('r')
    pl.savefig(ouF)
    inFile.close()
开发者ID:hanice,项目名称:EMBL,代码行数:26,代码来源:11-bar-plot.py

示例11: SingleTraitLM

def SingleTraitLM(inF1, inF2, ouF):

    geno_reader = gr.genotype_reader_tables(inF1)
    pheno_reader = phr.pheno_reader_tables(inF2)
    dataset = data.QTLData(geno_reader=geno_reader,pheno_reader=pheno_reader)
    geno = dataset.getGenotypes()
    position = dataset.getPos()
    pos,chromBounds = data_util.estCumPos(position=position,offset=0)

    ouFile = open(ouF, 'w')

    P_max = len(dataset.phenotype_ID)
    phenotype_ID = dataset.phenotype_ID[0:P_max]


    for p_ID in phenotype_ID[0:]:
        #phenotype_vals, sample_idx = dataset.getPhenotypes([pI], center=False)
        phenotype_vals, sample_idx = dataset.getPhenotypes([p_ID])
        phenotype_vals_ranks = preprocess.rankStandardizeNormal(phenotype_vals.values)
        lm_ranks = qtl.test_lm(snps=geno[sample_idx],pheno=phenotype_vals_ranks)
        pvalues_lm_ranks = pd.DataFrame(data=lm_ranks.pvalues.T,index=dataset.geno_ID,columns=[p_ID])
        pvt = lm_ranks.pvalues.T
        for i in xrange(pvt.shape[0]):
            p = pvt[i,0]
            if p <= SIG:
                ouFile.write('\t'.join([position['chrom'][i], str(position['pos'][i]), str(p), p_ID]) + '\n')
    ouFile.close()

    manhattonPlot(['NMD'],pvalues_lm_ranks,inF2,pos, chromBounds)

    pl.figure(figsize=[12,4])
    qqplot(pvalues_lm_ranks['NMD'].values)
    pl.savefig('pvalues-qqplot.pdf')
开发者ID:chw333,项目名称:StanfordSGTC,代码行数:33,代码来源:SingleTraitLM.py

示例12: density

def density(ouF, bandwidth):
    AX = []
    df = pd.read_table('Mouse_Gene_Promoter_Cov_ProteinCoding-Norm', header=0)
    
    Sample = df.columns[4:]
    #Sample2 = Sample
    Sample2 = [' '.join(x.split('_')[0:-1]) for x in df.columns[4:]]
    
    fig = plt.figure()
    ax = fig.add_axes([0.15,0.15,0.8,0.8])
    
    for i in range(4,df.shape[1]):
        AX.append(sns.kdeplot(np.log2(df.ix[:,i]), shade=True, color=LineColor(i-4), legend=True, label=GetLabel(i-4, Sample2), bw=bandwidth))
    '''
    patch1 = mpatches.Patch(color='r', label='Tspan8 negative MHCII low')
    patch2 = mpatches.Patch(color='b', label='Tspan8 negative MHCII high')
    patch3 = mpatches.Patch(color='g', label='Tspan8 positive MHCII low')
    patch4 = mpatches.Patch(color='m', label='Tspan8 positive MHCII high')
    plt.legend(handles=[patch1, patch2, patch3, patch4])
    '''
    ax.set_xlabel('Normalized number of reads (log2), bandwidth=%s'%bandwidth)
    ax.set_ylabel('Density of gene numbers')
    ax.set_xlim(0, ax.get_xlim()[1])
    
    plt.savefig(ouF +'-bw_'+ str(bandwidth) + '.pdf')
开发者ID:jiamaozheng,项目名称:StanfordSGTC,代码行数:25,代码来源:03-density.py

示例13: makeimg

def makeimg(wav):
	global callpath
	global imgpath

	fs, frames = wavfile.read(os.path.join(callpath, wav))
	
	pylab.ion()

	# generate specgram
	pylab.figure(1)
	
	# generate specgram
	pylab.specgram(
		frames,
		NFFT=256, 
		Fs=22050, 
		detrend=pylab.detrend_none,
		window=numpy.hamming(256),
		noverlap=192,
		cmap=pylab.get_cmap('Greys'))
	
	x_width = len(frames)/fs
	
	pylab.ylim([0,11025])
	pylab.xlim([0,round(x_width,3)-0.006])
	
	img_path = os.path.join(imgpath, wav.replace(".wav",".png"))

	pylab.savefig(img_path)
	
	return img_path
开发者ID:tomauer,项目名称:nfc_tweet,代码行数:31,代码来源:nfc_images.py

示例14: __call__

    def __call__(self, n):
        if len(self.f.shape) == 3:
            # f = f[x,v,t], 2 dim in phase space
            ft = self.f[n,:,:]
            pylab.pcolormesh(self.X, self.V, ft.T, cmap = 'jet')
            pylab.colorbar()
            pylab.clim(0,0.38) # for Landau test case
            pylab.grid()
            pylab.axis([self.xmin, self.xmax, self.ymin, self.ymax])
            pylab.xlabel('$x$', fontsize = 18)
            pylab.ylabel('$v$', fontsize = 18)
            pylab.title('$N_x$ = %d, $N_v$ = %d, $t$ = %2.1f' % (self.x.N, self.v.N, self.it*self.t.width))
            pylab.savefig(self.path + self.filename)
            pylab.clf()
            return None

        if len(self.f.shape) == 2:
            # f = f[x], 1 dim in phase space
            ft = self.f[n,:]
            pylab.plot(self.x.gridvalues,ft,'ob')
            pylab.grid()
            pylab.axis([self.xmin, self.xmax, self.ymin, self.ymax])
            pylab.xlabel('$x$', fontsize = 18)
            pylab.ylabel('$f(x)$', fontsize = 18)
            pylab.savefig(self.path + self.filename)
            return None
开发者ID:dsirajud,项目名称:IPython-notebooks,代码行数:26,代码来源:plots.py

示例15: Doplots_monthly

def Doplots_monthly(mypathforResults,PlottingDF,variable_to_fill, Site_ID,units,item):   
    ANN_label=str(item+"_NN")     #Do Monthly Plots
    print "Doing MOnthly  plot"
    #t = arange(1, 54, 1)
    NN_label='Fc'
    Plottemp = PlottingDF[[NN_label,item]][PlottingDF['day_night']!=1]
    #Plottemp = PlottingDF[[NN_label,item]].dropna(how='any')
    figure(1)
    pl.title('Nightime ANN v Tower by year-month for '+item+' at '+Site_ID)

    try:
	xdata1a=Plottemp[item].groupby([lambda x: x.year,lambda x: x.month]).mean()
	plotxdata1a=True
    except:
	plotxdata1a=False
    try:
	xdata1b=Plottemp[NN_label].groupby([lambda x: x.year,lambda x: x.month]).mean()
	plotxdata1b=True
    except:
	plotxdata1b=False 
    if plotxdata1a==True:
	pl.plot(xdata1a,'r',label=item) 
    if plotxdata1b==True:
	pl.plot(xdata1b,'b',label=NN_label)
    pl.ylabel('Flux')    
    pl.xlabel('Year - Month')       
    pl.legend()
    pl.savefig(mypathforResults+'/ANN and Tower plots by year and month for variable '+item+' at '+Site_ID)
    #pl.show()
    pl.close()
    time.sleep(1)
开发者ID:jberinge,项目名称:DINGO12,代码行数:31,代码来源:GPP_calc_v1b.py


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