如何使用偏移坐标正确绘制六边形?

4

这是我的代码:

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

请告诉我为什么我的六边形不是边缘对齐而是重叠在一起?我做错了什么吗?

1
“半径”太大了。看起来“RegularPolygon”将“半径”定义为中心点和每个顶点之间的距离。因此,您需要使用一些几何知识来计算出这个值,以便从中心到边缘的距离为1。 - mkrieger1
3个回答

6

使用余弦定理(针对等腰三角形,其角度为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()

0
非常简单,你的几何图形是错误的。你指定了半径为2/3。检查一下你的RegularPolygon文档;我认为你会发现正确的半径是0.577(sqrt(3) / 3)或接近这个值。

-1

正六边形的半径等于其边长。在这种情况下,适当的偏移量应为:offset = radius*3**0.5。如果半径为2/3,则偏移量应为1.1547k,其中k=-2,-1...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接