python - 使用 Regularpolycollection 在 Python 中创建六边形网格(u 矩阵)

标签 python numpy matplotlib

我正在尝试使用 RegularPolyCollection (参见下面的代码)创建一个六角网格,以便与 Python (3.4) 中的 u 矩阵一起使用,但遇到了两个问题:

  1. 六边形网格不紧密。当我绘制它时,六边形之间有空白区域。我可以通过调整窗口大小来解决此问题,但由于这是不可重现的,并且我希望所有绘图都具有相同的大小,因此这并不令人满意。但即使是这样,我也遇到了第二个问题。

  2. 顶部或右侧的六边形不适合图形并被裁剪。

我尝试了很多东西(改变图形大小、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()

最佳答案

See this topic

您还需要在轴上添加比例,例如 ax.axis([xmin, xmax, ymin, ymax])

关于python - 使用 Regularpolycollection 在 Python 中创建六边形网格(u 矩阵),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30133366/

相关文章:

python - 是否可以按降序使用 argsort?

python - 是否可以使用 numpy 乘法将字符串乘以整数?

python - Matplotlib 在保存 jpg 相对于 png 时显示不同的字体。为什么?

python - 如何在 Python 中设置直方图的 y 轴?

python - PDFlib文本提取工具的安装方法

python - NDVI值计算及图像处理

python - 将元组列表转换为数组或其他允许轻松切片的结构

python - 从文本文件中删除重复项

python - 使用 `scipy.sparse` 构建一个简单的线性系统

python - 更改 matplotlib 中的字体宽度