#绘制散点图将整个区域分为10乘10个网格,并统计每个网格中点的个数
from matplotlib import pyplot as plt
import matplotlib as mpl
import pandas as pd
import numpy as np
import os
import csv
mpl.rcParams["font.sans-serif"]=["LiSu"]
mpl.rcParams["axes.unicode_minus"]=False
#绘制散点图,x和y是data.csv中的两列,第一行为列名
data=pd.read_csv('C:/Users/Administrator/Desktop/工作/data.csv') #数据文件路径,数据中有x,y两列
plt.scatter(data['x'],data['y'],c="b",marker="o",linewidths=1,label='数据点') #绘制点(x,y)的散点图
#子区域划分
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
#plt.grid()
m=11 #m取11时,代表将区域划分为10*10个子区域
vlines = np.linspace(120.08, 120.12, m)
hlines = np.linspace(30.27, 30.38, m)
plt.hlines(hlines, min(vlines),max(vlines), colors='.25', linewidth=.75)
plt.vlines(vlines, min(hlines), max(hlines), colors='.25', linewidth=.75)
xs, ys = np.meshgrid(vlines[1:], hlines[:-1])
#从左到右,从下至上依次编号并显示
for i, (x, y) in enumerate(zip(xs.flatten(),ys.flatten())):
plt.text(x, y, str(i+1), horizontalalignment='right',verticalalignment='bottom')
plt.show()
#统计每个子区域中点的数量
x_min = 120.08
x_max = 120.12
y_min = 30.27
y_max = 30.38
x=[]
y=[]
n=0
for row1 in data['x']:
n+=1
x.append(row1)
for row2 in data['y']:
y.append(row2)
c={"x":x,'y':y}
data= pd.DataFrame(c)
# 使用矩阵分隔网格
# 生成网格ID column_num等于列数,row_num等于行数
def generalID(x,y,column_num,row_num):
# 若在范围外的点,返回-1
if x < x_min or x > x_max or y < y_min or y > y_max:
return -1
# 把范围根据列数等分切割
column = (x_max - x_min)/column_num
# 把范围根据行数等分切割
row = (y_max - y_min)/row_num
# 得到二维矩阵坐标索引,并转换为一维ID,即: 列坐标区域(向下取整)+ 1 + 行坐标区域 * 列数
return int((x-x_min)/column)+ 1 + int((y-y_min)/row) * column_num
## 对整个区域使用 10 X 10 划分
data['label'] = data.apply(lambda x: generalID(x['x'], x['y'],10,10), axis = 1)
a=data.label
b=np.sort(a)
D={}
for k in b:
D[k] = D.get(k, 0) +1
# print(D)
key=list(D.keys())
values =list(D.values())
name1=['location']
name2=['number']
test1=pd.DataFrame(columns=name1,data=key)
test2=pd.DataFrame(columns=name2,data=values)
'''test1.to_csv('C:/Users/Administrator/Desktop/data1.csv')
test2.to_csv('C:/Users/Administrator/Desktop/data2 .csv')'''
length=len(key)
for i in range(length):
print("编号为%d的区域中有%d个点"%(key[i],values[i]))