使用matplotlib显示六角网格

2024-06-07 10:15:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在某个方向上画一个六边形网格。 我使用了this答案中提供的函数,因此得到了如下结果:

enter image description here

现在,我想要一个六边形网格,它的方向不是这个,而是那个 其中一条边位于顶部,如下所示:

enter image description here

以下是用于绘制第一个图形的代码:

def draw_board(board, occupied):
    coord = board
    colors = ["blue" if x == 0 else "green" for x in occupied.values()]
    

# Horizontal cartesian coords
    hcoord = [c[0] for c in coord]

# Vertical cartersian coords
    vcoord = [2. * np.sin(np.radians(60)) * (c[1] - c[2]) /3. for c in coord]


    fig, ax = plt.subplots(1, figsize=(5, 5))
    ax.set_aspect('equal')

    # Add some coloured hexagons
    for x, y, c in zip(hcoord, vcoord, colors):
        color = c[0]
        hex = RegularPolygon((x, y), numVertices=6, radius=2. / 3, 
                             orientation=np.radians(30), facecolor = color,
                             alpha=0.3, edgecolor='k')
        ax.add_patch(hex)
        # Also add a text label

    # Also add scatter points in hexagon centres
    ax.scatter(hcoord, vcoord, alpha=0.3)

    plt.show()


Tags: inboardadd网格fornpcoordsax
1条回答
网友
1楼 · 发布于 2024-06-07 10:15:43

解决方案是将坐标从(x,y)翻转到(y,-x),然后旋转 网格中的每个六边形都是120度而不是30度。更新后的函数如下所示:

def draw_board(board, occupied):
coord = board
colors = ["blue" if x == 0 else "green" for x in occupied.values()]


# Horizontal cartesian coords
hcoord = [c[0] for c in coord]

# Vertical cartersian coords
vcoord = [2. * np.sin(np.radians(60)) * (c[1] - c[2]) /3. for c in coord]

for i in range(len(vcoord)):
    temp = vcoord[i]
    vcoord[i] = -hcoord[i]
    hcoord[i] = temp

fig, ax = plt.subplots(1, figsize=(10, 10))
ax.set_aspect('equal')

# Add some coloured hexagons
for x, y, c in zip(hcoord, vcoord, colors):
    color = c[0]
    hex = RegularPolygon((x, y), numVertices=6, radius=2. / 3, 
                         orientation=np.radians(120), facecolor = color,
                         alpha=0.3, edgecolor='k')
    ax.add_patch(hex)
    # Also add a text label

# Also add scatter points in hexagon centres
ax.scatter(hcoord, vcoord, alpha=0.3)

plt.show()

相关问题 更多 >

    热门问题