4

This is my code:

import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon
import numpy as np


offCoord = [[-2,-2],[-1,-2],[0,-2],[1,-2],[2,-2]]

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

for c in offCoord:
    hex = RegularPolygon((c[0], c[1]), numVertices=6, radius=2./3., alpha=0.2, edgecolor='k')
    ax.add_patch(hex)
plt.autoscale(enable = True)
plt.show()

Expected result vs actual result in the attached image

Expected result vs actual result

Please tell me why my hexagons are not lined up edge by edge but overlap each other? What am I doing wrong?

smci
  • 32,567
  • 20
  • 113
  • 146
Alex R
  • 83
  • 1
  • 8
  • 1
    `radius` is too large. It looks like `RegularPolygon` defines "radius" as the distance between the center and each of the vertices. So you need to use some geometry to figure out what this value should be so that the distance from the center to an edge is 1. – mkrieger1 Nov 26 '19 at 00:52

3 Answers3

6

Use law of cosines (for isosceles triangle with angle 120 degrees and sides r, r, and 1):

1 = r*r + r*r - 2*r*r*cos(2pi/3) = r*r + r*r + r*r = 3*r*r

r = sqrt(1/3)

triangle

This is the right code:

import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon
import numpy as np


offCoord = [[-2,-2],[-1,-2],[0,-2],[1,-2],[2,-2]]

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

for c in offCoord:
    # fix radius here
    hexagon = RegularPolygon((c[0], c[1]), numVertices=6, radius=np.sqrt(1/3), alpha=0.2, edgecolor='k')
    ax.add_patch(hexagon)
plt.autoscale(enable = True)
plt.show()
Marc
  • 712
  • 4
  • 7
Anatoliy R
  • 1,749
  • 2
  • 14
  • 20
0

Very simply, your geometry is wrong. You specified a radius of 2/3. Check your documentation for RegularPolygon; I think that you'll find the correct radius is 0.577 (sqrt(3) / 3) or something close to that.

Prune
  • 76,765
  • 14
  • 60
  • 81
-1

Radius of regular hexagon equals its side. In that case, the proper offset should be: offset = radius*3**0.5. If radius is 2/3, the offsets should be 1.1547k, where k=-2,-1...

Vasily Mitch
  • 357
  • 2
  • 10