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


Python pyplot.axes函数代码示例

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


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

示例1: make_shape

def make_shape(pts, max_output_len=100):
    """ 
    Args:
        pts: a tuple of points (x,y) to be interpolated
        max_output_len: the max number of points in the interpolated curve

    Returns:
        the pair of interpolated points (xnew,ynew)
    
    Raises:
        ValueError: pts defined a self-intersecting curve
    """
    assert len(pts[0]) == len(pts[1])
    pts = tuple(map(lambda x: np.append(x, x[0]), pts))
    fit_pts = interp(pts)
    if curve_intersects(fit_pts):
        raise ValueError("Curve is self-intersecting")

    if PLOT_SHAPE:
        plt.figure()
        plt.plot(pts[0],pts[1], 'x')
        plt.plot(fit_pts[0],fit_pts[1])
        plt.axes().set_aspect('equal', 'datalim')
        plt.show()
    
    
    sparse_pts = tuple(map(lambda ls: ls[::len(fit_pts[0]) // max_output_len + 1], fit_pts))
    return sparse_pts
开发者ID:evanprs,项目名称:thesis,代码行数:28,代码来源:xy_interpolation.py

示例2: drawVectors

def drawVectors(transformed_features, components_, columns, plt, scaled):
  if not scaled:
    return plt.axes() # No cheating ;-)

  num_columns = len(columns)

  # This funtion will project your *original* feature (columns)
  # onto your principal component feature-space, so that you can
  # visualize how "important" each one was in the
  # multi-dimensional scaling
  
  # Scale the principal components by the max value in
  # the transformed set belonging to that component
  xvector = components_[0] * max(transformed_features[:,0])
  yvector = components_[1] * max(transformed_features[:,1])

  ## visualize projections

  # Sort each column by it's length. These are your *original*
  # columns, not the principal components.
  important_features = { columns[i] : math.sqrt(xvector[i]**2 + yvector[i]**2) for i in range(num_columns) }
  important_features = sorted(zip(important_features.values(), important_features.keys()), reverse=True)
  print "Features by importance:\n", important_features

  ax = plt.axes()

  for i in range(num_columns):
    # Use an arrow to project each original feature as a
    # labeled vector on your principal component axes
    plt.arrow(0, 0, xvector[i], yvector[i], color='b', width=0.0005, head_width=0.02, alpha=0.75)
    plt.text(xvector[i]*1.2, yvector[i]*1.2, list(columns)[i], color='b', alpha=0.75)

  return ax
开发者ID:jonolsu,项目名称:classwork,代码行数:33,代码来源:m4PCA.assignment2.py

示例3: display_PER

    def display_PER(self):

        number_of_pkts = len(self.pcap_file)
        retransmission_pkts = 0

        for pkt in self.pcap_file:

            if (pkt[Dot11].FCfield & 0x8) != 0:
                retransmission_pkts += 1

        ans = (retransmission_pkts / number_of_pkts)*100
        ans = float("%.2f" % ans)
        labels = ['Standard packets', 'Retransmitted packets']
        sizes = [100.0 - ans,ans]


        colors = ['g', 'firebrick']

        # Make a pie graph
        plt.clf()
        plt.figure(num=1, figsize=(8, 6))
        plt.axes(aspect=1)
        plt.suptitle('Retransmitted packet', fontsize=14, fontweight='bold')
        plt.rcParams.update({'font.size': 13})
        plt.pie(sizes, labels=labels, autopct='%.2f%%', startangle=60, colors=colors, pctdistance=0.7, labeldistance=1.2)

        plt.show()
开发者ID:yarongoldshtein,项目名称:Wifi_Parser,代码行数:27,代码来源:ex3.py

示例4: POST

	def POST(self):
		data = web.data()
		query_data=json.loads(data)
		start_time=query_data["start_time"]
		end_time=query_data["end_time"]
		parameter=query_data["parameter"]
		query="SELECT "+parameter+",timestamp FROM jplug_data WHERE timestamp BETWEEN "+str(start_time)+" AND "+str(end_time)
		retrieved_data=list(db.query(query))
		LEN=len(retrieved_data)
		x=[0]*LEN
		y=[0]*LEN
		X=[None]*LEN
		for i in range(0,LEN):
			x[i]=retrieved_data[i]["timestamp"]
			y[i]=retrieved_data[i][parameter]
			X[i]=datetime.datetime.fromtimestamp(x[i],pytz.timezone(TIMEZONE))
			#print retrieved_data["timestamp"]
		with lock:
			figure = plt.gcf() # get current figure
			plt.axes().relim()
			plt.title(parameter+" vs Time")
			plt.xlabel("Time")
			plt.ylabel(units[parameter])
			plt.axes().autoscale_view(True,True,True)
			figure.autofmt_xdate()
			plt.plot(X,y)
			filename=randomword(12)+".jpg"
			plt.savefig("/home/muc/Desktop/Deployment/jplug_view_data/static/images/"+filename, bbox_inches=0,dpi=100)
			plt.close()
			web.header('Content-Type', 'application/json')
			return json.dumps({"filename":filename})
开发者ID:brianjgeiger,项目名称:Home_Deployment,代码行数:31,代码来源:smart_meter_csv.py

示例5: _scatter

def _scatter(actual, prediction, args):
    plt.figure()
    plt.plot(actual, prediction, 'b'+args['plot_scatter_marker'])
    xmin=min(actual)
    xmax=max(actual)
    ymin=min(prediction)
    ymax=max(prediction)
    diagxmin=min(math.fabs(x) for x in actual)
    diagymin=min(math.fabs(y) for y in prediction)
    diagpmin=min(diagxmin,diagymin)
    pmin=min(xmin,ymin)
    pmax=max(xmax,ymax)
    plt.plot([diagpmin,pmax],[diagpmin,pmax],'k-')
    if args['plot_identifier'] != 'NoName':
        plt.title(args['plot_identifier'])
    plt.xlabel('Observed')
    plt.ylabel('Modeled')
    if args['plot_performance_log'] == True:
        plt.yscale('log')
        plt.xscale('log')
    if args['plot_scatter_free'] != True:
        plt.axes().set_aspect('equal')
    if args['plot_dump'] == True:
        pfname=os.path.join(args['plot_dir'],args['plot_identifier']+'_eiger_scatter.pdf')
        plt.savefig(pfname,format="pdf")
    else:
        plt.show()
开发者ID:hoangt,项目名称:eiger,代码行数:27,代码来源:Eiger.py

示例6: plot_q_qhat

def plot_q_qhat(q, t):
    # Plot Potential Vorticity
    plt.clf()
    plt.subplot(2,1,1)
    plt.pcolormesh(xx/1e3,yy/1e3,q)
    plt.colorbar()
    plt.axes([-Lx/2e3, Lx/2e3, -Ly/2e3, Ly/2e3])
    name = "PV at t = %5.2f" % (t/(3600.0*24.0))
    plt.title(name)

    # compute power spectrum and shift ffts
    qe = np.vstack((q0,-np.flipud(q)))
    qhat = np.absolute(fftn(qe))
    kx = fftshift((parms.ikx/parms.ikx[0,1]).real)
    ky = fftshift((parms.iky/parms.iky[1,0]).real)
    qhat = fftshift(qhat)

    Sx, Sy = int(parms.Nx/2), parms.Ny
    Sk = 1.5

    # Plot power spectrum
    plt.subplot(2,1,2)
    #plt.pcolor(kx[Sy:Sy+20,Sx:Sx+20],ky[Sy:Sy+20,Sx:Sx+20],qhat[Sy:Sy+20,Sx:Sx+20])
    plt.pcolor(kx[Sy:int(Sk*Sy),Sx:int(Sk*Sx)],ky[Sy:int(Sk*Sy),Sx:int(Sk*Sx)],
               qhat[Sy:int(Sk*Sy),Sx:int(Sk*Sx)])
    plt.axis([0, 10, 0, 10])
    plt.colorbar()
    name = "PS at t = %5.2f" % (t/(3600.0*24.0))
    plt.title(name)

    plt.draw()
开发者ID:francispoulin,项目名称:usra-fluids,代码行数:31,代码来源:QG_pert_channel.py

示例7: test_plot_raw_psd

def test_plot_raw_psd():
    """Test plotting of raw psds."""
    import matplotlib.pyplot as plt
    raw = _get_raw()
    # normal mode
    raw.plot_psd(tmax=2.0)
    # specific mode
    picks = pick_types(raw.info, meg='mag', eeg=False)[:4]
    raw.plot_psd(picks=picks, area_mode='range')
    ax = plt.axes()
    # if ax is supplied:
    assert_raises(ValueError, raw.plot_psd, ax=ax)
    raw.plot_psd(picks=picks, ax=ax)
    plt.close('all')
    ax = plt.axes()
    assert_raises(ValueError, raw.plot_psd, ax=ax)
    ax = [ax, plt.axes()]
    raw.plot_psd(ax=ax)
    plt.close('all')
    # topo psd
    raw.plot_psd_topo()
    plt.close('all')
    # with a flat channel
    raw[5, :] = 0
    assert_raises(ValueError, raw.plot_psd)
开发者ID:mmagnuski,项目名称:mne-python,代码行数:25,代码来源:test_raw.py

示例8: plot_skew

def plot_skew(y_cv, preds, N = 50, Nmax = 20, start=0, detailed=True):
    '''
        plot the roc curves with different skews
        to see what the distribution of the data 
        is ...
    '''
    powers = np.linspace(start, N, Nmax)[1:]
    aucs   = []
    
    if detailed:
        plot_distribution(y_cv, preds**N)
    
    for xx, i in enumerate(powers):
        fpr, tpr, thresholds = metrics.roc_curve(y_cv, preds**i)
        roc_auc = metrics.auc(fpr, tpr)
        if detailed:
            plot_roc(fpr, tpr, roc_auc, newPlot=(xx==0), label='%.1f'%i, color=(i/N,0.5,1-i/N))
        aucs.append( roc_auc )

    if detailed:
        plt.legend()

    
    plt.figure(figsize=(4, 3))
    plt.axes([0.17, 0.18, 0.94-0.17, 0.96-0.18])
    plt.plot(powers, aucs, 's')
    intPowers = np.linspace(start, N, 100)[1:]

    # plt.plot(intPowers, np.poly1d(np.polyfit(powers, aucs, 2))( intPowers ), color='black' )
    plt.xlabel('power')
    plt.ylabel('AUC')

    return powers, aucs
开发者ID:sankhaMukherjee,项目名称:amazonEmployeeAccess,代码行数:33,代码来源:plots.py

示例9: display

def display(ncube, ngrid, path):
	# Time delay before displaying new plot.
	delay = 0.001

	# Determines the number of files over which to loop. 
	# NOTE: These files must be the only files in the directory for this approach to work.
	files = os.listdir(path)
	numFiles = len(files)

	# Prepares the plot to be displayed.
	pl.ion()
	pl.figure(1)

	# Loops over all files and extracts the component-based data.
	for i in xrange(1, numFiles + 1):
		x, y, z, vx, vy, vz = np.genfromtxt(path + "TimeStamp" + str(i) + ".txt", dtype = float, unpack = True)

		# Plots x positions against y positions to get an xy-plane slice. 
		pl.scatter(x, y, s = 3)
		pl.axes().set_xlim((0., float(ngrid * ncube)))
		pl.axes().set_ylim((0., float(ngrid * ncube)))
		pl.xlabel("X Position")
		pl.ylabel("Y Position")
		pl.title("N-Body Simulation: 2D Slice")

		# Draws the plot and then delays the next iteration.
		pl.draw()
		time.sleep(delay)
		pl.clf()

	# Closes the plot at the very end.
	pl.close(1)
开发者ID:emberson,项目名称:cta200nbody,代码行数:32,代码来源:DisplayParticles.py

示例10: add_clusters

    def add_clusters(self, cl_class, num_clusters, cl_color):
        mypatches=[]
        for i,(x,y) in enumerate(self.coords):
            if cl_class[i] == Cluster.NO_CLUSTER:
                continue
            
            if self.lattice == Lattice.Hex:
                patch = RegularPolygon((x,-y), numVertices=6, radius=3,
                                             facecolor=cl_color[cl_class[i] - 1],
                                             edgecolor='none')
            else:
                patch = Rectangle((x, -y), 5.2, 5.2,
                                        facecolor=cl_color[cl_class[i] - 1],
                                        edgecolor='none')
            mypatches.append(patch)
         
        p = PatchCollection(mypatches, match_original=True)

        self.ax.add_collection(p)
        self.ax.autoscale_view()
        plt.axes().set_aspect('equal', 'datalim')
        # Double the size of the canvas
        current_figure = plt.gcf()
        w, h = current_figure.get_size_inches()
        current_figure.set_size_inches(w*2, h*2)
        # Shrink current axis by 20% to make space for the legend
        box = self.ax.get_position()
        self.ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
        
        handles = []
        for i in range(num_clusters):
            handles.append(plt.Line2D((0,1),(0,0), color=cl_color[i]))
        plt.legend(handles, [ "cluster " + str(x) for x in range(1, num_clusters + 1)],
                   loc='center left', bbox_to_anchor=(1, 0.5))
开发者ID:alessioU,项目名称:SOM4Proteins,代码行数:34,代码来源:grid.py

示例11: display

def display(workspace, **params):
        
        def update(val):
                vmax = smax.val
                vmin = smin.val
                im.set_clim(vmax=vmax, vmin=vmin)
                fig.canvas.draw_idle()
        
        fig = pylab.figure()
        '''displays a gather using imshow'''

        vmax = np.amax(workspace)
        vmin = np.amin(workspace)

        im = pylab.imshow(workspace.T, aspect='auto', cmap='Greys', vmax =vmax, vmin=vmin)
        pylab.colorbar()
        axcolor = 'lightgoldenrodyellow'
        axmax = pylab.axes([0.08, 0.06, 0.65, 0.01], axisbg=axcolor) #rect = [left, bottom, width, height] in normalized (0, 1) units
        smax = Slider(axmax, 'vmax', vmin, vmax, valinit=vmax)
        smax.on_changed(update)
        axmin = pylab.axes([0.08, 0.03, 0.65, 0.01], axisbg=axcolor) #rect = [left, bottom, width, height] in normalized (0, 1) units
        smin = Slider(axmin, 'vmin', vmin, vmax, valinit=vmin)
        smin.on_changed(update)	
        smin.on_changed(update)
        
        pylab.show()
开发者ID:stuliveshere,项目名称:Seismic-Processing-Prac1,代码行数:26,代码来源:toolbox.py

示例12: generateToy

def generateToy():

  print 'loading values'
  if not os.path.isfile('values2.p'):
    z_data = np.loadtxt('values2.dat')
    pkl.dump( z_data, open( 'values2.p', "wb" ),pkl.HIGHEST_PROTOCOL )
  else:
    z_data = pkl.load(open('values2.p',"rb"))
  print 'loaded'

  #x = np.random.normal(size=1000)
  z_data_subset = z_data[0:20000]
  plot_range = [50,400]
  print 'max',max(z_data_subset),'min',min(z_data_subset)
  plt.yscale('log', nonposy='clip')
  plt.axes().set_ylim(0.0000001,0.17)
  hist(z_data_subset,range=plot_range,bins=100,normed=1,histtype='stepfilled',
      color=['lightgrey'], label=['100 bins'])
  #hist(z_data_subset,range=plot_range,bins='knuth',normed=1,histtype='step',linewidth=1.5,
  #    color=['navy'], label=['knuth'])
  hist(z_data_subset,range=plot_range,bins='blocks',normed=1,histtype='step',linewidth=2.0,
      color=['crimson'], label=['b blocks'])
  plt.legend()
  #plt.yscale('log', nonposy='clip')
  #plt.axes().set_ylim(0.0000001,0.17)
  plt.xlabel(r'$m_{\ell\ell}$ (GeV)')
  plt.ylabel('A.U.')
  plt.title(r'Z$\to\mu\mu$ Data')
  plt.savefig('z_data_hist_comp.png')
  plt.show()
开发者ID:brovercleveland,项目名称:BayesianBlocks,代码行数:30,代码来源:zExample.py

示例13: make_ax3

def make_ax3():
    paper_single(TW=8, AR=0.9)
    f = plt.figure()
    
    from matplotlib.ticker import NullFormatter, MaxNLocator

    nullfmt   = NullFormatter()         # no labels

    # definitions for the axes
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.6
    bottom_h = bottom+height+0.02
    left_h = left+width+0.02

    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom_h, width, 0.2]
    rect_histy = [left_h, bottom, 0.2, height]

    ax = plt.axes(rect_scatter)
    plt.minorticks_on()
    axx = plt.axes(rect_histx)
    plt.minorticks_on()
    axy = plt.axes(rect_histy)
    plt.minorticks_on()

    # no labels
    axx.xaxis.set_major_formatter(nullfmt)
    axy.yaxis.set_major_formatter(nullfmt)
    
    
    axy.xaxis.set_major_locator(MaxNLocator(3))
    axx.yaxis.set_major_locator(MaxNLocator(3))
    
    return f,ax,axx,axy
开发者ID:wllwen007,项目名称:utils,代码行数:34,代码来源:plot_util.py

示例14: generate

 def generate(self):
   # path = os.path.join(self.output_root, self.make_filename)
   plt.figure()
   plt.axes(**self.plot_settings['axis'])
   plt.imshow(self.frames(self.data), **self.plot_settings['image'])
   plt.savefig(self.path, bbox_inches="tight", pad_inches=0, format='png')
   plt.close()
开发者ID:smackesey,项目名称:sparco,代码行数:7,代码来源:feature.py

示例15: advance

 def advance(self, t, plotresult=False):
     y0 = self.concs * self.molWeight
     y0 = append(y0, self.thickness)
     yt = odeint(self.rightSideofODE, y0, t)
     if (plotresult):
         import matplotlib.pyplot as plt
         plt.figure()
         plt.axes([0.1, 0.1, 0.6, 0.85])
         plt.semilogy(t, yt)
         plt.ylabel('mass concentrations (kg/m3)')
         plt.xlabel('time(s)')
         #plt.legend(self.speciesnames)
         for i in range(len(self.speciesnames)):
             plt.annotate(
                 self.speciesnames[i], (t[-1], yt[-1, i]),
                 xytext=(20, -5),
                 textcoords='offset points',
                 arrowprops=dict(arrowstyle="-"))
         plt.show()
     self.thickness = yt[-1][-1]
     ytt = yt[-1][:-1]
     #        for iii in range(len(ytt)):
     #            if ytt[iii]<0:
     #                ytt[iii]=0.
     molDens = ytt / self.molWeight
     self.concs = molDens
     self.molFrac = molDens / sum(molDens)
     self.massFrac = ytt / sum(ytt)
开发者ID:weasky,项目名称:LiquidGasSimulation,代码行数:28,代码来源:evapor.py


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