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


Python pylab.savefig方法代码示例

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


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

示例1: plot_hits

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def plot_hits(filename_fil, filename_dat):
    """ Plot the hits in a .dat file. """
    table = find_event.read_dat(filename_dat)
    print(table)

    plt.figure(figsize=(10, 8))
    N_hit = len(table)
    if N_hit > 10:
        print("Warning: More than 10 hits found. Only plotting first 10")
        N_hit = 10

    for ii in range(N_hit):
        plt.subplot(N_hit, 1, ii+1)
        plot_event.plot_hit(filename_fil, filename_dat, ii)
    plt.tight_layout()
    plt.savefig(filename_dat.replace('.dat', '.png'))
    plt.show() 
开发者ID:UCBerkeleySETI,项目名称:turbo_seti,代码行数:19,代码来源:test_turbo_seti.py

示例2: train

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def train(self):
        # self.load_model('./save_model/cartpole_a3c.h5')
        agents = [Agent(i, self.actor, self.critic, self.optimizer, self.env_name, self.discount_factor,
                        self.action_size, self.state_size) for i in range(self.threads)]

        for agent in agents:
            agent.start()

        while True:
            time.sleep(20)

            plot = scores[:]
            pylab.plot(range(len(plot)), plot, 'b')
            pylab.savefig("./save_graph/cartpole_a3c.png")

            self.save_model('./save_model/cartpole_a3c.h5') 
开发者ID:rlcode,项目名称:reinforcement-learning,代码行数:18,代码来源:cartpole_a3c.py

示例3: summarise_reads

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def summarise_reads(path):
    """Count reads in all files in path"""

    resultfile = os.path.join(path, 'read_stats.csv')
    files = glob.glob(os.path.join(path,'*.fastq'))
    vals=[]
    rl=[]
    for f in files:
        label = os.path.splitext(os.path.basename(f))[0]
        s = utils.fastq_to_dataframe(f)
        l = len(s)
        vals.append([label,l])
        print (label, l)

    df = pd.DataFrame(vals,columns=['path','total reads'])
    df.to_csv(resultfile)
    df.plot(x='path',y='total reads',kind='barh')
    plt.tight_layout()
    plt.savefig(os.path.join(path,'total_reads.png'))
    #df = pd.concat()
    return df 
开发者ID:dmnfarrell,项目名称:smallrnaseq,代码行数:23,代码来源:analysis.py

示例4: plot_evaluation_episode_reward

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def plot_evaluation_episode_reward():
	pylab.clf()
	sns.set_context("poster")
	pylab.plot(0, 0)
	episodes = [0]
	average_scores = [0]
	median_scores = [0]
	for n in xrange(len(csv_evaluation)):
		params = csv_evaluation[n]
		episodes.append(params[0])
		average_scores.append(params[1])
		median_scores.append(params[2])
	pylab.plot(episodes, average_scores, sns.xkcd_rgb["windows blue"], lw=2)
	pylab.xlabel("episodes")
	pylab.ylabel("average score")
	pylab.savefig("%s/evaluation_episode_average_reward.png" % args.plot_dir)

	pylab.clf()
	pylab.plot(0, 0)
	pylab.plot(episodes, median_scores, sns.xkcd_rgb["windows blue"], lw=2)
	pylab.xlabel("episodes")
	pylab.ylabel("median score")
	pylab.savefig("%s/evaluation_episode_median_reward.png" % args.plot_dir) 
开发者ID:musyoku,项目名称:double-dqn,代码行数:25,代码来源:experiment.py

示例5: main

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def main():

    l2_base_dir = '/media/admin228/00027E210001A5BD/train_pytorch/change_detection/CMU/prediction_cons/l2_5,6,7/roc'
    cos_base_dir = '/media/admin228/00027E210001A5BD/train_pytorch/change_detection/CMU/prediction_cons/dist_cos_new_5,6,7/roc'
    CSF_dir = os.path.join(l2_base_dir)
    CSF_fig_dir = os.path.join(l2_base_dir,'fig.png')
    end_number = 22
    csf_conv5_l2_ls,csf_fc6_l2_ls,csf_fc7_l2_ls,x_l2 = get_csf_ls(l2_base_dir,end_number)
    csf_conv5_cos_ls,csf_fc6_cos_ls,csf_fc7_cos_ls,x_cos = get_csf_ls(cos_base_dir,end_number)
    Fig = pylab.figure()
    setFigLinesBW(Fig)
    #pylab.plot(x,csf_conv4_ls, color='k',label= 'conv4')
    pylab.plot(x_l2,csf_conv5_l2_ls, color='m',label= 'l2:conv5')
    pylab.plot(x_l2,csf_fc6_l2_ls, color = 'b',label= 'l2:fc6')
    pylab.plot(x_l2,csf_fc7_l2_ls, color = 'g',label= 'l2:fc7')
    pylab.plot(x_cos,csf_conv5_cos_ls, color='c',label= 'cos:conv5')
    pylab.plot(x_cos,csf_fc6_cos_ls, color = 'r',label= 'cos:fc6')
    pylab.plot(x_cos,csf_fc7_cos_ls, color = 'y',label= 'cos:fc7')
    pylab.legend(loc='lower right', prop={'size': 10})
    pylab.ylabel('RMS Contrast', fontsize=14)
    pylab.xlabel('Epoch', fontsize=14)
    pylab.savefig(CSF_fig_dir) 
开发者ID:gmayday1997,项目名称:SceneChangeDet,代码行数:24,代码来源:plot_contrast_sensitive.py

示例6: plot

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def plot(ifile, varkey, options, before='', after=''):
    import pylab as pl
    outpath = getattr(options, 'outpath', '.')
    var = ifile.variables[varkey]
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 1:
        raise ValueError(
            'Plots can have only 1 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    exec(before)
    ax = pl.gca()
    print(varkey, end='')
    if options.logscale:
        ax.set_yscale('log')

    ax.plot(var[:].squeeze())
    ax.set_xlabel('unknown')
    ax.set_ylabel(getattr(var, 'standard_name',
                          varkey).strip() + ' ' + var.units.strip())
    fmt = 'png'
    figpath = os.path.join(outpath + '_1d_' + varkey + '.' + fmt)
    exec(after)
    pl.savefig(figpath)
    print('Saved fig', figpath)
    return figpath 
开发者ID:barronh,项目名称:pseudonetcdf,代码行数:27,代码来源:pncview.py

示例7: on_epoch_end

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close() 
开发者ID:hello-sea,项目名称:DeepLearning_Wavelet-LSTM,代码行数:23,代码来源:image_ocr.py

示例8: _plot_example

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def _plot_example(xv, yv, b):
    """Plot for debugging purposes."""

    matplotlib.rcParams['font.family'] = "serif"
    matplotlib.rcParams['font.sans-serif'] = "Times"
    matplotlib.rcParams["legend.edgecolor"] = "None"
    matplotlib.rcParams["axes.spines.top"] = False
    matplotlib.rcParams["axes.spines.bottom"] = True
    matplotlib.rcParams["axes.spines.left"] = True
    matplotlib.rcParams["axes.spines.right"] = False
    matplotlib.rcParams['axes.grid'] = True
    matplotlib.rcParams['axes.grid.axis'] = 'both'
    matplotlib.rcParams['axes.grid.which'] = 'major'
    matplotlib.rcParams['legend.edgecolor'] = '1.0'
    plt.plot(xv[:, 113], yv[:, 113], 'ko')
    plt.plot(xv[:, 113], xv[:, 113] * b[113, 1] + b[113, 0], 'nneighbors')
    # plt.plot(x[113], x[113]*b[113, 1] + b[113, 0], 'ro')
    plt.grid(True)
    plt.xlabel('Radiance, $\mu{W }nm^{-1} sr^{-1} cm^{-2}$')
    plt.ylabel('Reflectance')
    plt.show(block=True)
    plt.savefig('empirical_line.pdf') 
开发者ID:isofit,项目名称:isofit,代码行数:24,代码来源:empirical_line.py

示例9: plotdata

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def plotdata(obsmode,spectrum,val,odict,sdict,
             instr,fieldname,outdir,outname):
    isetting=P.isinteractive()
    P.ioff()

    P.clf()
    P.plot(obsmode,val,'.')
    P.ylabel('(pysyn-syn)/syn')
    P.xlabel('obsmode')
    P.title("%s: %s"%(instr,fieldname))
    P.savefig(os.path.join(outdir,outname+'_obsmode.ps'))

    P.clf()
    P.plot(spectrum,val,'.')
    P.ylabel('(pysyn-syn)/syn')
    P.xlabel('spectrum')
    P.title("%s: %s"%(instr,fieldname))
    P.savefig(os.path.join(outdir,outname+'_spectrum.ps'))

    matplotlib.interactive(isetting) 
开发者ID:spacetelescope,项目名称:pysynphot,代码行数:22,代码来源:doscalars.py

示例10: save

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def save(GUI):
    global txtResultPath
    if GUI:
        import pylab as pl
        import nest.raster_plot
        import nest.voltage_trace
        logger.debug("Saving IMAGES into {0}".format(SAVE_PATH))
        for key in spikedetectors:
            try:
                nest.raster_plot.from_device(spikedetectors[key], hist=True)
                pl.savefig(f_name_gen(SAVE_PATH, "spikes_" + key.lower()), dpi=dpi_n, format='png')
                pl.close()
            except Exception:
                print(" * * * from {0} is NOTHING".format(key))
    txtResultPath = SAVE_PATH + 'txt/'
    logger.debug("Saving TEXT into {0}".format(txtResultPath))
    if not os.path.exists(txtResultPath):
        os.mkdir(txtResultPath)
    for key in spikedetectors:
        save_spikes(spikedetectors[key], name=key)
    with open(txtResultPath + 'timeSimulation.txt', 'w') as f:
        for item in times:
            f.write(item) 
开发者ID:research-team,项目名称:NEUCOGAR,代码行数:25,代码来源:func.py

示例11: draw_graph_row

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def draw_graph_row(graphs,
                   index=0,
                   contract=True,
                   n_graphs_per_line=5,
                   size=4,
                   xlim=None,
                   ylim=None,
                   **args):
    """draw_graph_row."""
    dim = len(graphs)
    size_y = size
    size_x = size * n_graphs_per_line * args.get('size_x_to_y_ratio', 1)
    plt.figure(figsize=(size_x, size_y))

    if xlim is not None:
        plt.xlim(xlim)
        plt.ylim(ylim)
    else:
        plt.xlim(xmax=3)

    for i in range(dim):
        plt.subplot(1, n_graphs_per_line, i + 1)
        graph = graphs[i]
        draw_graph(graph,
                   size=None,
                   pos=graph.graph.get('pos_dict', None),
                   **args)
    if args.get('file_name', None) is None:
        plt.show()
    else:
        row_file_name = '%d_' % (index) + args['file_name']
        plt.savefig(row_file_name,
                    bbox_inches='tight',
                    transparent=True,
                    pad_inches=0)
        plt.close() 
开发者ID:fabriziocosta,项目名称:EDeN,代码行数:38,代码来源:__init__.py

示例12: dendrogram

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def dendrogram(data,
               vectorizer,
               method="ward",
               color_threshold=1,
               size=10,
               filename=None):
    """dendrogram.

    "median","centroid","weighted","single","ward","complete","average"
    """
    data = list(data)
    # get labels
    labels = []
    for graph in data:
        label = graph.graph.get('id', None)
        if label:
            labels.append(label)
    # transform input into sparse vectors
    data_matrix = vectorizer.transform(data)

    # labels
    if not labels:
        labels = [str(i) for i in range(data_matrix.shape[0])]

    # embed high dimensional sparse vectors in 2D
    from sklearn import metrics
    from scipy.cluster.hierarchy import linkage, dendrogram
    distance_matrix = metrics.pairwise.pairwise_distances(data_matrix)
    linkage_matrix = linkage(distance_matrix, method=method)
    plt.figure(figsize=(size, size))
    dendrogram(linkage_matrix,
               color_threshold=color_threshold,
               labels=labels,
               orientation='right')
    if filename is not None:
        plt.savefig(filename)
    else:
        plt.show() 
开发者ID:fabriziocosta,项目名称:EDeN,代码行数:40,代码来源:__init__.py

示例13: save_plot

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def save_plot(self, filename):
        plt.ion()
        targarr = np.array(self.targvalue)
        self.posi[0].set_xdata(self.wt_positions[:,0])
        self.posi[0].set_ydata(self.wt_positions[:,1])
        while len(self.plotel)>0:
            self.plotel.pop(0).remove()
        self.plotel = self.shape_plot.plot(np.array([self.wt_positions[[i,j],0] for i, j in self.elnet_layout.keys()]).T,
                                   np.array([self.wt_positions[[i,j],1]  for i, j in self.elnet_layout.keys()]).T, 'y-', linewidth=1)
        for i in range(len(self.posb)):
            self.posb[i][0].set_xdata(self.iterations)
            self.posb[i][0].set_ydata(targarr[:,i])
            self.legend.texts[i].set_text('%s = %8.2f'%(self.targname[i], targarr[-1,i]))
        self.objf_plot.set_xlim([0, self.iterations[-1]])
        self.objf_plot.set_ylim([0.5, 1.2])
        if not self.title == '':
            plt.title('%s = %8.2f'%(self.title, getattr(self, self.title)))
        plt.draw()
        #print self.iterations[-1] , ': ' + ', '.join(['%s=%6.2f'%(self.targname[i], targarr[-1,i]) for i in range(len(self.targname))])
        with open(self.result_file+'.results','a') as f:
            f.write( '%d:'%(self.inc) + ', '.join(['%s=%6.2f'%(self.targname[i], targarr[-1,i]) for i in range(len(self.targname))]) +
                '\n')
        #plt.show()
        #plt.savefig(filename)
        display(plt.gcf())
        #plt.show()
        clear_output(wait=True) 
开发者ID:DTUWindEnergy,项目名称:TOPFARM,代码行数:29,代码来源:plot.py

示例14: plotGraph

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def plotGraph(x, y, z, filename):
	v = [0,5000,0,200]
	plt.axis(v)
	plt.scatter(x, y, alpha = 0.10, cmap=plt.cm.cool, edgecolors='None')
	# plt.colorbar()
	pylab.savefig(filename, bbox_inches = 0)
	plt.clf()

#scale input data and plot graphs 
开发者ID:pratiknarang,项目名称:peershark,代码行数:11,代码来源:plotGraphs.py

示例15: saveBEVImageWithAxes

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import savefig [as 别名]
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''
    
    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)
    
    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')
    
    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])
    
    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])
        
    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear() 
开发者ID:MarvinTeichmann,项目名称:KittiSeg,代码行数:34,代码来源:helper.py


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