• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python pyplot.scatter函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: altitude

def altitude():
	global alt, i
	
	#we want to create temporary file to parse, so that we don't mess with the nmea.txt file
	f1 = open('temp.txt', 'w') #creates and opens a writable txt file
	f1.truncate() #erase contents of file
	shutil.copyfile('nmea.txt', 'temp.txt') #copy nmea.txt to temp.txt
	f1.close() #close writable file
	
	f1 = open('temp.txt', 'r') #open and read only
	try: #best to use try/finally so that the file opens and closes correctly
		for line in f1: #read each line in temp.txt
			if(line[4] == 'G'): # fifth character in $GPGGA
				if(len(line) > 50): # when there is a lock, the sentence gets filled with data
					#print line
					gpgga = nmea.GPGGA()
					gpgga.parse(line)
					alt = gpgga.antenna_altitude
					i +=1 #increment the counter
					print i
					print alt
					plt.scatter(x=[i], y=[float(alt)], s = 1, c='r') #plot each point
	finally:
		f1.close()
	i=0
	
	#axis is autoscaled
	plt.ylabel('meters')
	plt.xlabel('counts')
	plt.title('ALTITUDE')
	plt.show()
开发者ID:freedom1370,项目名称:ONE,代码行数:31,代码来源:gpsmap.py


示例2: work

    def work(self):
        self.worked = True
        kwargs = dict(
                weights=self.weights,
                mus=self.mus,
                sigmas=self.sigmas,
                low=self.low,
                high=self.high,
                q=self.q,
                )
        samples = GMM1(rng=self.rng,
                size=(self.n_samples,),
                **kwargs)
        samples = np.sort(samples)
        edges = samples[::self.samples_per_bin]
        #print samples

        pdf = np.exp(GMM1_lpdf(edges[:-1], **kwargs))
        dx = edges[1:] - edges[:-1]
        y = 1 / dx / len(dx)

        if self.show:
            plt.scatter(edges[:-1], y)
            plt.plot(edges[:-1], pdf)
            plt.show()
        err = (pdf - y) ** 2
        print np.max(err)
        print np.mean(err)
        print np.median(err)
        if not self.show:
            assert np.max(err) < .1
            assert np.mean(err) < .01
            assert np.median(err) < .01
开发者ID:AshBT,项目名称:hyperopt,代码行数:33,代码来源:test_tpe.py


示例3: plot_2d_simple

def plot_2d_simple(data,y=None):
    if y==None:
        plt.scatter(data[:,0],data[:,1],s=50)
    else:
        nY=len(y)
        Ycol=[collist[ y.astype(int)[i] -1 % len(collist)] for i in xrange(nY)]
        plt.scatter(data[:,0],data[:,1],c=Ycol,s=40 )
开发者ID:Banaei,项目名称:ces-ds,代码行数:7,代码来源:utils.py


示例4: tuning

def tuning(x, y, err=None, smooth=None, ylabel=None, pal=None):
    """
    Plot a tuning curve
    """
    if smooth is not None:
        xs, ys = smoothfit(x, y, smooth)
        plt.plot(xs, ys, linewidth=4, color="black", zorder=1)
    else:
        ys = asarray([0])
    if pal is None:
        pal = sns.color_palette("husl", n_colors=len(x) + 6)
        pal = pal[2 : 2 + len(x)][::-1]
    plt.scatter(x, y, s=300, linewidth=0, color=pal, zorder=2)
    if err is not None:
        plt.errorbar(x, y, yerr=err, linestyle="None", ecolor="black", zorder=1)
    plt.xlabel("Wall distance (mm)")
    plt.ylabel(ylabel)
    plt.xlim([-2.5, 32.5])
    errTmp = err
    errTmp[isnan(err)] = 0
    rng = max([nanmax(ys), nanmax(y + errTmp)])
    plt.ylim([0 - rng * 0.1, rng + rng * 0.1])
    plt.yticks(linspace(0, rng, 3))
    plt.xticks(range(0, 40, 10))
    sns.despine()
    return rng
开发者ID:speron,项目名称:sofroniew-vlasov-2015,代码行数:26,代码来源:plots.py


示例5: draw

def draw(data, classes, model, resolution=100):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
    two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        z.append(predict(model, inputs[i])[0])
    result = np.array(z).reshape(xx1.shape)
    
    plt.contourf(xx1, xx2, result, cmap=mycm)
    plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm)
    
    t = np.zeros(15)
    for i in range(15):
        if i < 5:
            t[i] = 0
        elif i < 10:
            t[i] = 1
        else:
            t[i] = 2
    plt.scatter(model[:, 0], model[:, 1], s=150, c=t, cmap=mycm)
    
    plt.xlim([0, 10])
    plt.ylim([0, 10])
    
    plt.show()
开发者ID:jayshonzs,项目名称:ESL,代码行数:31,代码来源:LVQ.py


示例6: plot_dpi_dpr_distribution

def plot_dpi_dpr_distribution(args, dpis, dprs, diagnoses):
    print log.INFO, 'Plotting estimate distributions...'
    diagnoses = np.array(diagnoses)
    diagnoses[(0.25 <= diagnoses) & (diagnoses <= 0.75)] = 0.5

    # Setup plot
    fig, ax = plt.subplots()
    pt.setup_axes(plt, ax)

    biomarkers_str = args.method if args.biomarkers is None else ', '.join(args.biomarkers)
    ax.set_title('DP estimation using {0} at {1}'.format(biomarkers_str, ', '.join(args.visits)))
    ax.set_xlabel('DP')
    ax.set_ylabel('DPR')

    plt.scatter(dpis, dprs, c=diagnoses, edgecolor='none', s=25.0,
                vmin=0.0, vmax=1.0, cmap=pt.progression_cmap,
                alpha=0.5)

    # Plot legend
    # noinspection PyUnresolvedReferences
    rects = [mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_cn + (0.5,), linewidth=0),
             mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_mci + (0.5,), linewidth=0),
             mpl.patches.Rectangle((0, 0), 1, 1, fc=pt.color_ad + (0.5,), linewidth=0)]
    labels = ['CN', 'MCI', 'AD']
    legend = ax.legend(rects, labels, fontsize=10, ncol=len(rects), loc='upper center', framealpha=0.9)
    legend.get_frame().set_edgecolor((0.6, 0.6, 0.6))

    # Draw or save the plot
    plt.tight_layout()
    if args.plot_file is not None:
        plt.savefig(args.plot_file, transparent=True)
    else:
        plt.show()
    plt.close(fig)
开发者ID:aschmiri,项目名称:DiseaseProgressionModel,代码行数:34,代码来源:estimate_progressions.py


示例7: plot

def plot(i, pcanc, lr, pp, labelFlag, Y):
    if len(str(i)) == 1:
        fig = plt.figure(i)
    else:
        fig = plt.subplot(i)
    if pcanc == 0:
        plt.title(
                  ' learning_rate: ' + str(lr)
                + ' perplexity: ' + str(pp))
        print("Plotting tSNE")
    else:
        plt.title(
                  'PCA-n_components: ' + str(pcanc)
                + ' learning_rate: ' + str(lr)
                + ' perplexity: ' + str(pp))
        print("Plotting PCA-tSNE")
    plt.scatter(Y[:, 0], Y[:, 1], c=colors)
    if labelFlag == 1:
        for label, cx, cy in zip(y, Y[:, 0], Y[:, 1]):
            plt.annotate(
                label.decode('utf-8'),
                xy = (cx, cy),
                xytext = (-10, 10),
                fontproperties=font,
                textcoords = 'offset points', ha = 'right', va = 'bottom',
                bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.9))
                #arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
    ax.xaxis.set_major_formatter(NullFormatter())
    ax.yaxis.set_major_formatter(NullFormatter())
    plt.axis('tight')
    print("Done.")
开发者ID:CORDEA,项目名称:niconico-visualization,代码行数:31,代码来源:mds_plot_hamming.py


示例8: plot_data

def plot_data(models,dataframe,flag = 0):
    """need good and bad models, plots all the data"""
    if flag == 0:
        for key in models[0]:
            g=dataframe[(dataframe['module_category']==key[0]) & \
            (dataframe['component_category']==key[1])]
            plt.scatter(g['time'],g['number_repair'],c =np.random.rand(3,1))
            plt.xlabel("Time")
            plt.ylabel("number of repairs")
            plt.title("%s, and %s" %(key[0], key[1]))
            plt.show()
    if flag ==1:
        
        for key in models[1]:
            g=dataframe[(dataframe['module_category']==key[0]) & \
            (dataframe['component_category']==key[1])]
            plt.scatter(g['time'],g['number_repair'],c =np.random.rand(3,1))
            plt.xlabel("Time")
            plt.ylabel("number of repairs")
            
            if models[1][key] == [1,1,1]:
                plt.title("too little data: %s, and %s" %(key[0],key[1]))
            else:
                plt.title("no curve fit: %s, and %s" %(key[0], key[1]))
            plt.show()
开发者ID:joseph-yi,项目名称:asus_all,代码行数:25,代码来源:asus.py


示例9: visualizeEigenvalues

def visualizeEigenvalues(eVal, verboseLevel):
	real = []
	imag = []

	for z in eVal:
		rp = z.real
		im = z.imag
		if not (rp == np.inf or rp == - np.inf) \
				and not (im == np.inf or im == - np.inf):
			real.append(rp)
			imag.append(im)

	if verboseLevel>=1:
		print("length of regular real values=" + str(len(real)))
		print("length of regular imag values=" + str(len(imag)))
		print("minimal real part=" + str(min(real)), "& maximal real part=" + str(max(real)))
		print("minimal imag part=" + str(min(imag)), "& maximal imag part=" + str(max(imag)))
	if verboseLevel==2:
		print("all real values:", str(real))
		print("all imag values:", str(imag))


	# plt.scatter(real[4:],img[4:])
	plt.scatter(real, imag)
	plt.grid(True)
	plt.xlabel("realpart")
	plt.ylabel("imagpart")
	plt.xlim(-10, 10)
	plt.ylim(-10, 10)
	plt.show()
开发者ID:MattWise,项目名称:1a-Analysis,代码行数:30,代码来源:testing.py


示例10: export

  def export(self, query, n_topics, n_words, title="PCA Export", fname="PCAExport"):
    vec = DictVectorizer()
    
    rows = topics_to_vectorspace(self.model, n_topics, n_words)
    X = vec.fit_transform(rows)
    pca = skPCA(n_components=2)
    X_pca = pca.fit(X.toarray()).transform(X.toarray())
    
    match = []
    for i in range(n_topics):
      topic = [t[1] for t in self.model.show_topic(i, len(self.dictionary.keys()))]
      m = None
      for word in topic:
        if word in query:
          match.append(word)
          break

    pyplot.figure()
    for i in range(X_pca.shape[0]):
      pyplot.scatter(X_pca[i, 0], X_pca[i, 1], alpha=.5)
      pyplot.text(X_pca[i, 0], X_pca[i, 1], s=' '.join([str(i), match[i]]))  
     
    pyplot.title(title)
    pyplot.savefig(fname)
     
    pyplot.close()
开发者ID:PonteIneptique,项目名称:Siena-2015,代码行数:26,代码来源:Gensim.py


示例11: scatter

def scatter(frame, var1, var2, var3=None, reg=False, **args):
    import matplotlib.cm as cm

    if type(frame) is copper.Dataset:
        frame = frame.frame
    x = frame[var1]
    y = frame[var2]

    if var3 is None:
        plt.scatter(x.values, y.values, **args)
    else:
        options = list(set(frame[var3]))
        for i, option in enumerate(options):
            f = frame[frame[var3] == option]
            x = f[var1]
            y = f[var2]
            c = cm.jet(i/len(options),1)
            plt.scatter(x, y, c=c, label=option, **args)
            plt.legend()

    if reg:
        slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
        line = slope * x + intercept # regression line
        plt.plot(x, line, c='r')

    plt.xlabel(var1)
    plt.ylabel(var2)
开发者ID:vibster,项目名称:copper,代码行数:27,代码来源:base.py


示例12: plot_contour_with_labels

    def plot_contour_with_labels(contour, frame_index=0):
        """
        Makes a beautiful plot with all the points labeled.

        Parameters:
        One frame's worth of a contour

        """
        contour_x = contour[:, 0, frame_index]
        contour_y = contour[:, 1, frame_index]
        plt.plot(contour_x, contour_y, 'r', lw=3)
        plt.scatter(contour_x, contour_y, s=35)
        labels = list(str(l) for l in range(0, len(contour_x)))
        for label_index, (label, x, y), in enumerate(
                zip(labels, contour_x, contour_y)):
            # Orient the label for the first half of the points in one direction
            # and the other half in the other
            if label_index <= len(contour_x) // 2 - \
                    1:  # Minus one since indexing
                xytext = (20, -20)                     # is 0-based
            else:
                xytext = (-20, 20)
            plt.annotate(
                label, xy=(
                    x, y), xytext=xytext, textcoords='offset points', ha='right', va='bottom', bbox=dict(
                    boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(
                    arrowstyle='->', connectionstyle='arc3,rad=0'))  # , xytext=(0,0))
开发者ID:KristianPeltonen,项目名称:open-worm-analysis-toolbox,代码行数:27,代码来源:normalized_worm.py


示例13: kmeans

def kmeans(points, k):
    
    centroids = random.sample(points, k)

    allColors = list(colors.cnames.keys())

    iterations = 0
    oldCentroids = None

    while not shouldStop(oldCentroids, centroids, iterations):
        oldCentroids = centroids
        iterations += 1
        
        #we need numpy arrays to do some cool linalg stuff
        points = np.array(points)
        centroids = np.array(centroids)
        labels = getLabels(points, centroids)
        
        centroids = getCentroids(points, labels, k)
    #plotting centroids as a red star
    x, y = zip(*centroids)
    plt.scatter(x,y, marker = '*', color = 'r', s = 80)
    
    #life is a coloring book so lets put colors on stuff
    counter = 0
    for centroid in labels.keys():
        for point in labels[centroid]:
                plt.scatter(point[0], point[1], color = allColors[counter])
       
       #6 was chosen to avoid white, white is apparantly some multiple of 5
        counter += 6

    print (iterations)
    return centroids
开发者ID:tadams2,项目名称:School-Work,代码行数:34,代码来源:Clustering.py


示例14: plotscatterdate

def plotscatterdate(x,y):
    plt.scatter(x,y)   
    plt.xlim(0,)
    plt.xlabel('Number of Railways')
    plt.ylabel('Price in Pounds')
    plt.title('Scatter of Price against Number of Railways')
    plt.show()
开发者ID:dwj26,项目名称:SummerDataChallenge,代码行数:7,代码来源:house+price+geo.py


示例15: plot_words

def plot_words (V,labels=None,color='b',mark='o',fa='bottom'):
	W = tsne(V,2)
	i = 0
	plt.scatter(W[:,0], W[:,1],c=color,marker=mark,s=50.0)
	for label,x,y in zip(labels, W[:,0], W[:,1]):
		plt.annotate(label.decode('utf8'), xy=(x,y), xytext=(-1,1), textcoords='offset points', ha= 'center', va=fa, bbox=dict(boxstyle='round,pad=0.1', fc='white', alpha=0))
		i += 1
开发者ID:VMijangos,项目名称:Lineal_Trans,代码行数:7,代码来源:truquitVer1.py


示例16: plt_data

def plt_data():
    t = [[0,1], [1,0], [1, 1], [0, 0]]
    t2 = [1, 1, 1, 0]
    X = np.array(t)
    Y = np.array(t2)

    h = .02  # step size in the mesh

    logreg = linear_model.LogisticRegression(C=1e5)

    # we create an instance of Neighbours Classifier and fit the data.
    logreg.fit(X, Y)
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure(1, figsize=(4, 3))
    plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)
    plt.xlabel('Sepal length')
    plt.ylabel('Sepal width')

    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())

    plt.show()
开发者ID:robsonfgomes,项目名称:Redes-Neurais,代码行数:35,代码来源:main.py


示例17: create_plots

def create_plots(iterations, data, M, step_size):
    NN_b, NN_a, E = steepest_decent_training(iterations, data, M, step_size)

    X = data[:,0]
    X_cont = np.arange(-10,10,0.1)
    
    t = data[:,1]
    Y = [NN_a(np.array([[x],[1]]))[0] for x in X_cont]
    f = np.vectorize(lambda(x): sin(x) / x)

    plt.figure(1)
    plt.plot(X_cont,Y,label='Neural network \n (M = %d)' % M)
    plt.plot(X_cont,f(X_cont),label='sinc(x)')
    plt.legend()
    plt.savefig('images/nn_vs_real_%d_%d.%s' % (iterations,M,img_format), format=img_format)

    plt.figure(2)
    plt.plot(X_cont,Y,label='Neural network \n (M = %d)' % M)
    plt.scatter(X,t,color='red',label='Training data')
    plt.legend()
    plt.savefig('images/nn_vs_training_%d_%d.%s' % (iterations,M,img_format), format=img_format)

    plt.figure(3)
    plt.plot(E, label='Error (M = %d)' % M)
    plt.yscale('log')
    plt.legend()
    plt.savefig('images/error_%d_%d.%s' % (iterations,M,img_format), format=img_format)
    
    plt.show()
开发者ID:jongisli,项目名称:statml_assignment3,代码行数:29,代码来源:neuralnetwork.py


示例18: plot_convergence

def plot_convergence():

    data = np.loadtxt("smooth-error.out")

    nx = data[:,0]
    aerr = data[:,1]

    ax = plt.subplot(111)
    ax.set_xscale('log')
    ax.set_yscale('log')

    plt.scatter(nx, aerr, marker="x", color="r")
    plt.plot(nx, aerr[0]*(nx[0]/nx)**2, "--", color="k")

    plt.xlabel("number of zones")
    plt.ylabel("L2 norm of abs error")

    plt.title(r"convergence for smooth advection problem", fontsize=11)

    f = plt.gcf()
    f.set_size_inches(5.0,5.0)

    plt.xlim(8,256)

    plt.savefig("smooth_converge.eps", bbox_inches="tight")
开发者ID:MrHelloBye,项目名称:pyro2,代码行数:25,代码来源:convergence_plot.py


示例19: regress_show4

def regress_show4( yEv, yEv_calc, disp = True, graph = True, plt_title = None, ms_sz = None):

	# if the output is a vector and the original is a metrix, 
	# the output is translated to a matrix. 

	r_sqr, RMSE, MAE, DAE = estimate_accuracy4( yEv, yEv_calc, disp = disp)
	
	if graph:
		#plt.scatter( yEv.tolist(), yEv_calc.tolist())	
		plt.figure()	
		if ms_sz is None:
			ms_sz = max(min( 6000 / yEv.shape[0], 8), 3)
		# plt.plot( yEv.tolist(), yEv_calc.tolist(), '.', ms = ms_sz) # Change ms 
		plt.scatter( yEv.tolist(), yEv_calc.tolist(), s = ms_sz) 
		ax = plt.gca()
		lims = [
			np.min([ax.get_xlim(), ax.get_ylim()]),  # min of both axes
			np.max([ax.get_xlim(), ax.get_ylim()]),  # max of both axes
		]
		# now plot both limits against eachother
		#ax.plot(lims, lims, 'k-', alpha=0.75, zorder=0)
		ax.plot(lims, lims, '-', color = 'pink')
		plt.xlabel('Experiment')
		plt.ylabel('Prediction')
		if plt_title is None:
			plt.title( '$r^2$={0:.1e}, RMSE={1:.1e}, MAE={2:.1e}, MedAE={3:.1e}'.format( r_sqr, RMSE, MAE, DAE))
		elif plt_title != "": 
			plt.title( plt_title)
		# plt.show()
	
	return r_sqr, RMSE, MAE, DAE
开发者ID:jskDr,项目名称:jamespy_py3,代码行数:31,代码来源:jutil.py


示例20: base

def base(Point):#画出基础
    for x in np.linspace(Point[0] - 0.3, Point[0] + 0.3, 100):
        plt.scatter(x, Point[1], color='k', s=0.1, marker='o', label=str)
    for t in np.linspace(Point[0] - 0.2, Point[0] + 0.2, 3):
        P1 = [t, Point[1]]
        P2 = [t - 0.15, Point[1] - 0.25]
        line(P1, P2, width=0.1)
开发者ID:THUzhangga,项目名称:-,代码行数:7,代码来源:矩阵位移法.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pyplot.sci函数代码示例发布时间:2022-05-27
下一篇:
Python pyplot.sca函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap