我正在尝试使用 RegularPolyCollection(参见下面的代码)在 Python (3.4) 中创建一个与 u 矩阵一起使用的六角形网格,但遇到了两个问题:
六边形网格不紧。当我绘制它时,六边形之间有空白。我可以通过调整窗口大小来解决这个问题,但由于这是不可重现的,而且我希望我的所有绘图都具有相同的大小,所以这并不令人满意。但即使是,我也遇到了第二个问题。
上六边形或右六边形不适合图中,已被裁剪。
我尝试了很多东西(改变图形大小、subplot_adjust()、不同的区域、不同的 d 值等),我开始明白了疯狂的!感觉解决方案应该很简单,但我就是找不到!
import SOM
import matplotlib.pyplot as plt
from matplotlib.collections import RegularPolyCollection
import numpy as np
import matplotlib.cm as cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
m = 3 # The height
n = 3 # The width
# Some maths regarding hexagon geometry
d = 10
s = d/(2*np.cos(np.pi/3))
h = s*(1+2*np.sin(np.pi/3))
r = d/2
area = 3*np.sqrt(3)*s**2/2
# The center coordinates of the hexagons are calculated.
x1 = np.array([d*x for x in range(2*n-1)])
x2 = x1 + r
x3 = x2 + r
y = np.array([h*x for x in range(2*m-1)])
c = []
for i in range(2*m-1):
if i%4 == 0:
c += [[x,y[i]] for x in x1]
if (i-1)%2 == 0:
c += [[x,y[i]] for x in x2]
if (i-2)%4 == 0:
c += [[x,y[i]] for x in x3]
c = np.array(c)
# The color of the hexagons
d_matrix = np.zeros(3*3)
# Creating the figure
fig = plt.figure(figsize=(5, 5), dpi=100)
ax = fig.add_subplot(111)
# The collection
coll = RegularPolyCollection(
numsides=6, # a hexagon
rotation=0,
sizes=(area,),
edgecolors = (0, 0, 0, 1),
array= d_matrix,
cmap = cm.gray_r,
offsets = c,
transOffset = ax.transData,
)
ax.add_collection(coll, autolim=True)
ax.axis('off')
ax.autoscale_view()
plt.show()
请您参考如下方法:
你还需要在轴上添加刻度,比如 ax.axis([xmin, xmax, ymin, ymax])
