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


Python pylab.close函数代码示例

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


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

示例1: 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

示例2: test_simple_gen

 def test_simple_gen(self):
     self_con = .8
     other_con = 0.05
     g = self.gen.gen_stoch_blockmodel(min_degree=1, blocks=5, self_con=self_con, other_con=other_con,
                                       powerlaw_exp=2.1, degree_seq='powerlaw', num_nodes=1000, num_links=3000)
     deg_hist = vertex_hist(g, 'total')
     res = fit_powerlaw.Fit(g.degree_property_map('total').a, discrete=True)
     print 'powerlaw alpha:', res.power_law.alpha
     print 'powerlaw xmin:', res.power_law.xmin
     if len(deg_hist[0]) != len(deg_hist[1]):
         deg_hist[1] = deg_hist[1][:len(deg_hist[0])]
     print 'plot degree dist'
     plt.plot(deg_hist[1], deg_hist[0])
     plt.xscale('log')
     plt.xlabel('degree')
     plt.ylabel('#nodes')
     plt.yscale('log')
     plt.savefig('deg_dist_test.png')
     plt.close('all')
     print 'plot graph'
     pos = sfdp_layout(g, groups=g.vp['com'], mu=3)
     graph_draw(g, pos=pos, output='graph.png', output_size=(800, 800),
                vertex_size=prop_to_size(g.degree_property_map('total'), mi=2, ma=30), vertex_color=[0., 0., 0., 1.],
                vertex_fill_color=g.vp['com'],
                bg_color=[1., 1., 1., 1.])
     plt.close('all')
     print 'init:', self_con / (self_con + other_con), other_con / (self_con + other_con)
     print 'real:', gt_tools.get_graph_com_connectivity(g, 'com')
开发者ID:floriangeigl,项目名称:tools,代码行数:28,代码来源:gt_tools_tests.py

示例3: ploter

def ploter(X,n,name,path,real_ranges = None):
	'''
	Graph plotting module. Very basic, so feel free to modify it.
	'''
	try: import matplotlib.pylab as plt
	except ImportError: 
		print '\nMatplotlib is not installed! Either install it, or deselect graph option.\n'	
		return 1

	lll = 1+len(X)/n
	fig = plt.figure(figsize=(16,14),dpi=100)
	for x in xrange(0,len(X),n):
		iii = 1+x/n
		ax = fig.add_subplot(lll,1,iii)
       
		if real_ranges != None:
			for p in real_ranges:
				if p[0] in range(x,x+n) and p[1] in range(x,x+n): ax.axvspan(p[0]%(n), p[1]%(n), facecolor='g', alpha=0.5)
				elif p[0] in range(x,x+n) and p[1] > x+n: ax.axvspan(p[0]%(n), n, facecolor='g', alpha=0.5)
				elif p[0] < x and p[1] in range(x,x+n): ax.axvspan(0, p[1]%(n), facecolor='g', alpha=0.5)
				elif p[0] < x and p[1] > x+n: ax.axvspan(0, n, facecolor='g', alpha=0.5)

		ax.plot(X[x:x+n],'r-')

		ax.set_xlim(0.,n)
		ax.set_ylim(0.,1.)
		ax.set_xticklabels(range(x,x+750,100)) #(x,x+n/5,x+2*n/5,x+3*n/5,x+4*n/5,x+5*n/5) )
                
	plt.savefig(path+'HMM_'+name+'.png')
	plt.close()
开发者ID:Chalcone,项目名称:ClusterFinder,代码行数:30,代码来源:Predict.py

示例4: plot_q

def plot_q(frame,file_prefix='claw',file_format='petsc',path='./_output/',plot_pcolor=True,plot_slices=True,slices_xlimits=None):
    import sys
    sys.path.append('.')
    import gaussian_1d

    sol=Solution(frame,file_format=file_format,read_aux=False,path=path,file_prefix=file_prefix)
    x=sol.state.grid.x.centers
    mx=len(x)

    bathymetry = 0.5
    eta=sol.state.q[0,:] + bathymetry

    if frame < 10:
        str_frame = "00"+str(frame)
    elif frame < 100:
        str_frame = "0"+str(frame)
    else:
        str_frame = str(frame)

    fig = pl.figure(figsize=(40,10))
    ax = fig.add_subplot(111)
    ax.set_aspect(aspect=1)
    ax.plot(x,eta)
    #pl.title("t= "+str(sol.state.t),fontsize=20)
    #pl.xticks(size=20); pl.yticks(size=20)
    #pl.xlim([0, gaussian_1d.Lx])
    pl.ylim([0.5, 1.0])
    pl.xlim([0., 4.0])
    #pl.axis('equal')
    pl.savefig('./_plots/eta_'+str_frame+'_slices.png')
    pl.close()
开发者ID:ketch,项目名称:shallow_water_periodic_bathymetry,代码行数:31,代码来源:plot_1D.py

示例5: viz_birth_proposal_2D

def viz_birth_proposal_2D(curModel, newModel, ktarget, freshCompIDs,
                          title1='Before Birth',
                          title2='After Birth'):
  ''' Create before/after visualization of a birth move (in 2D)
  '''
  from ..viz import GaussViz, BarsViz
  from matplotlib import pylab

  fig = pylab.figure()
  h1 = pylab.subplot(1,2,1)

  if curModel.obsModel.__class__.__name__.count('Gauss'):
    GaussViz.plotGauss2DFromHModel(curModel, compsToHighlight=ktarget)
  else:
    BarsViz.plotBarsFromHModel(curModel, compsToHighlight=ktarget, figH=h1)
  pylab.title(title1)
    
  h2 = pylab.subplot(1,2,2)
  if curModel.obsModel.__class__.__name__.count('Gauss'):
    GaussViz.plotGauss2DFromHModel(newModel, compsToHighlight=freshCompIDs)
  else:
    BarsViz.plotBarsFromHModel(newModel, compsToHighlight=freshCompIDs, figH=h2)
  pylab.title(title2)
  pylab.show(block=False)
  try: 
    x = raw_input('Press any key to continue >>')
  except KeyboardInterrupt:
    import sys
    sys.exit(-1)
  pylab.close()
开发者ID:agile-innovations,项目名称:refinery,代码行数:30,代码来源:BirthMove.py

示例6: plot_BIC_score

def plot_BIC_score(BIC_SCORE, path):
    xlabel('|C|')
    ylabel('BIC score')
    grid(True)
    plot(BIC_SCORE)
    savefig(os.path.join(path, 'BIC.png'))
    close()
开发者ID:AndersHqst,项目名称:PyMTV,代码行数:7,代码来源:mtv_results.py

示例7: plot_running_time

def plot_running_time(running_time, path):
    xlabel('|C|')
    ylabel('MTV iteration in secs.')
    grid(True)
    plot([x for x in range(len(running_time))], running_time)
    savefig(os.path.join(path, 'running_time.png'))
    close()
开发者ID:AndersHqst,项目名称:PyMTV,代码行数:7,代码来源:mtv_results.py

示例8: plot_predlinks_roc

def plot_predlinks_roc(infile, outfile):
    preddf = pickle.load(open(infile, 'r'))['df']

    preddf['tp'] = preddf['t_t'] / preddf['t_tot']
    preddf['fp'] = preddf['f_t'] / preddf['f_tot']
    preddf['frac_wrong'] = 1.0 - (preddf['t_t'] + preddf['f_f']) / (preddf['t_tot'] + preddf['f_tot'])

    f = pylab.figure(figsize=(2, 2))
    ax = f.add_subplot(1, 1, 1)
    
    # group by cv set
    for row_name, cv_df in preddf.groupby('cv_idx'):
        cv_df_m = cv_df.groupby('pred_thold').mean().sort('fp')
        ax.plot(cv_df_m['fp'], cv_df_m['tp'] , c='k', alpha=0.3)
    

    fname = infile[0].split('-')[0]
    ax.set_title(fname)
    ax.set_xticks([0.0, 1.0])
    ax.set_yticks([0.0, 1.0])
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    f.savefig(outfile)

    pylab.close(f)
开发者ID:ericmjonas,项目名称:connectodiscovery,代码行数:25,代码来源:sparkanalysis.py

示例9: plot_df

    def plot_df(self,show=False):
        from matplotlib import pylab as plt 

        if self.afp is None:
            print 'afp not initilized. call update afp'
            return -1

        linecords,td,df,rtn,minmaxy = self.afp

        formatter = PlotDateFormatter(df.index)
        #fig = plt.figure()
        #ax = plt.addsubplot()
        fig, ax = plt.subplots()
        ax.xaxis.set_major_formatter(formatter)
    
        ax.plot(np.arange(len(df)), df['p'])

        for cord in linecords:
            plt.plot(cord[0],cord[1],color='red')

        fig.autofmt_xdate()
        plt.xlim(-10,len(df.index) + 10)
        plt.ylim(df.p.min() - 10,df.p.max() + 10)
        plt.grid(ax)
        #if show:
        #    plt.show()
        
        #"{0}{1}.png".format("./data/",datetime.datetime.strftime(datetime.datetime.now(),'%Y%M%m%S'))
        if self.plot_file:
            save_path = self.plot_file.format(self.symbol)
            if os.path.exists(os.path.dirname(save_path)):
                plt.savefig(save_path)
                
        plt.clf()
        plt.close()
开发者ID:mushtaqck,项目名称:WklyTrd,代码行数:35,代码来源:vehicle.py

示例10: analyze

def analyze(title, x, y, func, func_title):
    print('-' * 80)
    print(title)
    print('x: %s:%s %s' % (list(x.shape), x.dtype, [x.min(), x.max()]))
    print('y: %s:%s %s' % (list(y.shape), y.dtype, [y.min(), y.max()]))

    popt, pcov = curve_fit(func, x, y)
    print('popt=%s' % popt)
    print('pcov=\n%s' % pcov)

    a, b = popt
    print('a=%e' % a)
    print('b=%e' % b)
    print(func_title(a, b))
    xf = np.linspace(x.min(), x.max(), 100)
    yf = func(xf, a, b)
    print('xf: %s:%s %s' % (list(xf.shape), xf.dtype, [xf.min(), xf.max()]))
    print('yf: %s:%s %s' % (list(yf.shape), yf.dtype, [yf.min(), yf.max()]))

    plt.title(func_title(a, b))
    # plt.xlim(0, x.max())
    # plt.ylim(0, y.max())
    plt.semilogx(x, y, label='data')
    plt.semilogx(xf, yf, label='fit')
    plt.legend(loc='best')
    plt.savefig('%s.png' % title)
    plt.close()
开发者ID:peterwilliams97,项目名称:go-work,代码行数:27,代码来源:compute_pt.py

示例11: check_HDF5

def check_HDF5(size=64):
    """
    Plot images with landmarks to check the processing
    """

    # Get hdf5 file
    hdf5_file = os.path.join(data_dir, "CelebA_%s_data.h5" % size)

    with h5py.File(hdf5_file, "r") as hf:
        data_color = hf["training_color_data"]
        data_lab = hf["training_lab_data"]
        data_black = hf["training_black_data"]
        for i in range(data_color.shape[0]):
            fig = plt.figure()
            gs = gridspec.GridSpec(3, 1)
            for k in range(3):
                ax = plt.subplot(gs[k])
                if k == 0:
                    img = data_color[i, :, :, :].transpose(1,2,0)
                    ax.imshow(img)
                elif k == 1:
                    img = data_lab[i, :, :, :].transpose(1,2,0)
                    img = color.lab2rgb(img)
                    ax.imshow(img)
                elif k == 2:
                    img = data_black[i, 0, :, :] / 255.
                    ax.imshow(img, cmap="gray")
            gs.tight_layout(fig)
            plt.show()
            plt.clf()
            plt.close()
开发者ID:MiG-Kharkov,项目名称:DeepLearningImplementations,代码行数:31,代码来源:make_dataset.py

示例12: test_ThroughputLines

    def test_ThroughputLines(self):
        # # Plot Throughput Lines

        required_files = [
            "throughput_sep_lines_static." + img_extn,
            "throughput_sep_lines_all_mobile." + img_extn
        ]
        for f in required_files:
            try:
                os.remove(f)
            except:
                pass

        cb.latexify(columns=_texcol, factor=_texfac)

        for mobility in mobilities:
            df = get_mobility_stats(mobility)
            fig = plt.figure(facecolor='white')
            ax = fig.add_subplot(1, 1, 1)
            for (k, g), ls in zip(df.groupby('separation'), itertools.cycle(["-", "--", "-.", ":"])):
                ax.plot(g.rate, g.throughput, label=k, linestyle=ls)
            ax.legend(loc="upper left")
            ax.set_xlabel("Packet Emission Rate (pps)")
            ax.set_ylabel("Avg. Throughput (bps)")
            fig.tight_layout()
            savefig(fig,"throughput_sep_lines_{0}".format(
                mobility), transparent=True, facecolor='white')
            plt.close(fig)

        for f in required_files:
            self.assertTrue(os.path.isfile(f))
            self.generated_files.append(f)
开发者ID:andrewbolster,项目名称:aietes,代码行数:32,代码来源:test_Thesis_lazy.py

示例13: test_PhysicalNodeLayout

    def test_PhysicalNodeLayout(self):
        # # Graph: Physical Layout of Nodes
        required_files = ["s1_layout." + img_extn]
        #
        for f in required_files:
            try:
                os.remove(f)
            except:
                pass

        figsize = cb.latexify(columns=_texcol, factor=_texfac)

        base_config = aietes.Simulation.populate_config(
            aietes.Tools.get_config('bella_static.conf'),
            retain_default=True
        )
        texify = lambda t: "${0}_{1}$".format(t[0], t[1])
        node_positions = {texify(k): np.asarray(v['initial_position'], dtype=float) for k, v in
                          base_config['Node']['Nodes'].items() if 'initial_position' in v}
        node_links = {0: [1, 2, 3], 1: [0, 1, 2, 3, 4, 5], 2: [0, 1, 5], 3: [0, 1, 4], 4: [1, 3, 5], 5: [1, 2, 4]}

        fig = cb.plot_nodes(node_positions, figsize=figsize, node_links=node_links, radius=0, scalefree=True,
                            square=True)
        fig.tight_layout(pad=0.3)
        savefig(fig,"s1_layout", transparent=True)
        plt.close(fig)

        for f in required_files:
            self.assertTrue(os.path.isfile(f))
            self.generated_files.append(f)
开发者ID:andrewbolster,项目名称:aietes,代码行数:30,代码来源:test_Thesis_lazy.py

示例14: plot_ea

def plot_ea(frame1, filt_df, dst_path, uplift_rate, riv_case):
    f = plt.figure()
    ax = filt_df.plot(x='ApatiteHeAge', y='Elevation', style='o-', ax=f.gca())

    plt.title('Age-Elevation')
    plt.xlabel('ApatiteHeAge [Ma]')
    plt.ylabel('Elevation [Km]')

    #tread line
    sup_age, slope, r_square = find_max_treadline(filt_df, uplift_rate * np.sin(np.deg2rad(60)), riv_case)
    x = filt_df[filt_df['ApatiteHeAge'] < sup_age]['ApatiteHeAge']
    y = filt_df[filt_df['ApatiteHeAge'] < sup_age]['Points:2']
    z = np.polyfit(x, y, 1)
    p = np.poly1d(z)

    # plt.legend(point_lables, loc='best', fontsize=10)
    # n = np.linspace(min(frame1[frame1['Points:2'] > min(frame1['Points:2'])]['ApatiteHeAge']), max(frame1['ApatiteHeAge']), 21)
    n = np.linspace(min(filt_df[filt_df['Points:2'] >= min(filt_df['Points:2'])]['ApatiteHeAge']), max(filt_df['ApatiteHeAge']), 21)
    plt.plot(n, p(n) - min(frame1['Points:2']),'-r')
    ax.text(np.mean(n), np.mean(p(n) - min(frame1['Points:2'])), 'y=%.6fx + b'%(z[0]), fontsize = 20)

    txs = np.linspace(np.round(min(filt_df['Elevation'])), np.ceil(max(filt_df['Elevation'])), 11)
    lebs = ['0'] + [str(i) for i in txs[1:]]
    plt.yticks(txs, list(reversed(lebs)))
    plt.savefig(dst_path)
    plt.close()
    return z[0]
开发者ID:imalkov82,项目名称:Model-Executor,代码行数:27,代码来源:pecanalysis.py

示例15: threeD_gridplot

def threeD_gridplot(nodes, save=False, savefile=''):
    r"""Function to plot in 3D a series of grid points.

    :type nodes: list of tuples
    :param nodes: List of tuples of the form (lat, long, depth)
    :type save: bool
    :param save: if True will save without plotting to screen, if False \
        (default) will plot to screen but not save
    :type savefile: str
    :param savefile: required if save=True, path to save figure to.
    """
    lats = []
    longs = []
    depths = []
    for node in nodes:
        lats.append(float(node[0]))
        longs.append(float(node[1]))
        depths.append(float(node[2]))
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(lats, longs, depths)
    ax.set_ylabel("Latitude (deg)")
    ax.set_xlabel("Longitude (deg)")
    ax.set_zlabel("Depth(km)")
    ax.get_xaxis().get_major_formatter().set_scientific(False)
    ax.get_yaxis().get_major_formatter().set_scientific(False)
    if not save:
        plt.show()
        plt.close()
    else:
        plt.savefig(savefile)
    return
开发者ID:cjhopp,项目名称:EQcorrscan,代码行数:32,代码来源:plotting.py


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