s3nti3ntB
s3nti3ntB

Reputation: 431

Displaying a hexagonal grid with matplotlib

I am trying to draw a hexagonal grid in a certain orientation. I had used a function which was provided in this answer, so i got something like this:

enter image description here

Now, i would like to have a hexagon grid which is not oriented in this way, but that one of the edges is on top, like this:

enter image description here

Here is the code used to plot the first graph:

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

Upvotes: 2

Views: 3908

Answers (1)

s3nti3ntB
s3nti3ntB

Reputation: 431

The solution is to flip the coordinates from (x, y) to (y, -x), and to rotate each hexagon in our grid for 120 degrees instead of 30. The updated function looks like 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]

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

Upvotes: 3

Related Questions