【问题标题】:Displaying a hexagonal grid with matplotlib使用 matplotlib 显示六边形网格
【发布时间】:2021-08-06 08:12:34
【问题描述】:

我正在尝试在某个方向上绘制一个六边形网格。 我使用了this 答案中提供的函数,所以我得到了这样的结果:

现在,我想要一个不以这种方式定向的六边形网格,但是那个 的边缘在顶部,如下所示:

这是用于绘制第一张图的代码:

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()

【问题讨论】:

    标签: python matplotlib math graph


    【解决方案1】:

    解决方法是将坐标从(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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      相关资源
      最近更新 更多