python - 使用 matplotlib 显示六边形网格
问题描述
我正在尝试以某个方向绘制六边形网格。我使用了这个答案中提供的一个函数,所以我得到了这样的东西:
现在,我想要一个六边形网格,它不是以这种方式定向的,但其中一个边缘在顶部,如下所示:
这是用于绘制第一张图的代码:
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()
解决方案
解决方案是将坐标从 (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()
推荐阅读
- javascript - 如何将表格数据放入jQuery中的数组中?
- batch-file - 如何修复批处理文件中的 goto 问题
- django - 如何从 Django 模型中 ImageField 的图像目录中选择一个随机图像?
- android - 仅在从 android studio 的 Datepickerdialog 中选择之后,如何才能显示选定的日期和名称?
- c# - 模型中的虚拟字段在保存时出错
- pdf - 通过使用 Ghostscript 向 PDF 添加边距来缩放页面中的图像
- angular - Angular 2+ npm 启动问题
- abstract-syntax-tree - AST 节点中的“nosink”
- javascript - Collada 从未在 animate() 中定义
- javascript - 单击重置按钮时如何恢复输入框的默认值(即今天的日期或当前日期)?