如何正确绘制具有偏移坐标的六边形?
How to properly draw hexagons with offset coordinates?
这是我的代码:
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()
所附图片中的预期结果与实际结果
请问为什么我的六边形不是边排边而是互相重叠?
我做错了什么?
很简单,你的几何图形是错误的。您指定的半径为 2/3。检查您的文档 RegularPolygon
;我认为您会发现正确的半径是 0.577 (sqrt(3) / 3) 或接近于此的值。
正六边形的半径等于它的边。在这种情况下,正确的偏移量应该是:
offset = radius*3**0.5
。如果半径为 2/3,则偏移量应为 1.1547k,其中 k=-2,-1...
使用余弦定律(对于角为 120 度且边长为 r、r 和 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)
这是正确的代码:
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()
这是我的代码:
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()
所附图片中的预期结果与实际结果
请问为什么我的六边形不是边排边而是互相重叠? 我做错了什么?
很简单,你的几何图形是错误的。您指定的半径为 2/3。检查您的文档 RegularPolygon
;我认为您会发现正确的半径是 0.577 (sqrt(3) / 3) 或接近于此的值。
正六边形的半径等于它的边。在这种情况下,正确的偏移量应该是:
offset = radius*3**0.5
。如果半径为 2/3,则偏移量应为 1.1547k,其中 k=-2,-1...
使用余弦定律(对于角为 120 度且边长为 r、r 和 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)
这是正确的代码:
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()