六边形网格系统
在数据分析时,尤其是在数据可视化中,很多时候要用到网格划分,六边形网格以其优越的表现广泛应用。本文中,使用了python语言,做了简易的网格生成,及其颜色的填充,效果如下。这本文中的代码只能作为写代码时的一个参考。
代码中所需模块包有:
math
numy
matplotlib
Python代码如下
### Persus & Xie
### 网格系统
## 六边形网格
import math
import matplotlib.pyplot as plt
import numpy as np
def cal_r(x,y,xx,yy):
r = math.sqrt((xx-x)**2+(yy-y)**2)
return r
def cal_theta(x,y,x1,y1):
# calculate the point's angle
r = cal_r(x,y,x1,y1)
if x1-x>0 and y1-y >=0:
theta1 = math.asin((y1-y)/r)
elif x1-x>=0 and y1-y<0:
theta1 = math.pi*2+math.asin((y1-y)/r)
elif x1-x<0 and y1-y<=0 :
theta1 = math.pi-math.asin((y1-y)/r)
elif x1-x<=0 and y1-y>0 :
theta1 = math.pi-math.asin((y1-y)/r)
else:
theta1=0
# print("plot1.....")
return theta1
def polygon(x,y,n,r,co="teal"):
y2 = []
angle0 = 2*math.pi / n /2 #calculate the angle of r and the edge of the vertical
angle1 = np.arange(0,6*math.pi*2/n,math.pi*2/n) #calciulate the angle of spin
y0 = r * math.cos(angle0)+y # calculate the high of the edge
x0 = r*math.sin(angle0) #calculate the length of side
x2 = [-x0+x,x0+x]
xx = []
yy = []
for i in range(len(x2)):
y2.append(y0)
for j in angle1:
new_x = []
new_y = []
for i in range(len(x2)):
r = cal_r(x,y,x2[i],y2[i])
theta=cal_theta(x,y,x2[i],y2[i])
nx = math.cos( j+theta+math.pi/6)*r
ny = math.sin( j+theta+math.pi/6)*r
nnx = nx+x
nny = ny +y
#if nny >0:
new_x.append(nx+x)
new_y.append(ny+y)
if i %2 == 0:
xx.append(nx+x)
yy.append(ny+y)
plt.plot(new_x,new_y,c="k",lw=1)
plt.fill(xx,yy,alpha=0.9,color=co)
def grid_hexagon(x1=0,x2=10,y1=0,y2=10,n=6,r=2,color ="teal"):
"""
generate hexagon grid
"""
angle0 = 2*math.pi / n /2 #calculate the angle of r and the edge of the vertical
angle1 = np.arange(0,6*math.pi*2/n,math.pi*2/n) #calciulate the angle of spin
#y0 = r * math.cos(angle0)+y0 # calculate the high of the edge
# print(n,r,angle0)
x0 = r*math.sin(angle0)
print(x1,x2,y1,y2)
for i in range(int((x2+r*math.sqrt(3)-x1)/(r*math.sqrt(3)))):
#print(i)
#polygon(x1+i*r*math.sqrt(3),y1,6,r)
for j in range(int((y2+r*math.sqrt(3)-x1)/(r*math.sqrt(3)))):
if j%2 == 0:
polygon(x1+i*r*math.sqrt(3),y1+j*((x0+r)),6,r,color)
else:
#print(j)
polygon(x1+(i)*r*math.sqrt(3)+r*math.sqrt(3)/2,y1+j*((x0+r)),6,r,color)
#print(a)
plt.figure(figsize=[9,8])
#plt.xlim(-15,15)
#plt.ylim(-15,15)
grid_hexagon(0,5,0,5,6,2)
grid_hexagon(12,20,12,20,6,2,"#ff6163")
plt.savefig("hexagon.png",dpi=300,format="png")
plt.show()