关于python:4535

19次阅读

共计 1136 个字符,预计需要花费 3 分钟才能阅读完成。

import scipy.spatial as spt
import numpy as np
import matplotlib.pyplot as plt
plt.rc('font', family='simhei', size=10)    # 设置中文显示,字体大小
plt.rc('axes', unicode_minus=False)         # 该参数解决负号显示的问题


points = np.random.randint(1,20,(10,2))  # 生成 10 个二维坐标点,x 和 y 的取值范畴为 [1,20)
plt.scatter(x=points[:, 0], y=points[:, 1], s=150 ,color='red', marker='o')   # 标出所有样本点   s 代表 marker 的大小  留神前两个参数,不是坐标点,而是 x 坐标的汇合(二维矩阵 points 的第一列)和 y 坐标的汇合(二维矩阵 points 的第二列)# 执行查找函数
tree = spt.cKDTree(data=points)  

for point in points:
    distances, indexs = tree.query(point, k=2)  # 对每个坐标点,求出与它间隔最近的两个点(最近邻是它自身,要疏忽掉)# point 代表以后点,point[0] 即为以后点的 x 坐标,point[1] 即为以后点的 y 坐标
    # points[indexs[1]] 代表其余点中距离以后点最近的一个点,points[indexs[1]][0] 和 points[indexs[1]][1] 代表这个点的 x 和 y 坐标
    x = [point[0], points[indexs[1]][0]]
    y = [point[1], points[indexs[1]][1]]
    # plt.plot(x,y, color='black')    # 不带箭头的连线。留神前两个参数,不是坐标点,而是 x 坐标的汇合和 y 坐标的汇合
    plt.arrow(x= point[0],y= point[1], dx=points[indexs[1]][0]-point[0],  dy=points[indexs[1]][1]-point[1] ,width=0.1 ,length_includes_head=True, color='green')    # 带箭头的连线:https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.arrow.html 
    plt.text(sum(x)/2, sum(y)/2,fontsize=10, s="%.2f"%distances[1])  # 在连线上表明最短距离的值。因为 x 是两个点 x 坐标的汇合,所以 sum(x)/ 2 代表这条线的核心地位,在两头写(s 示意要书写的字符串)plt.show() # 展现图像

正文完
 0