在matplotlib中绘制六边形网格

5

我想绘制一个六边形网格的图形,最终结果应该看起来像蜂巢。然而,我使用matplotlib.collections.RegularPolyCollection时无法正确调整六边形的大小。有人能看出我做错了什么,或者提供另一个解决方案吗?我想象这已经被做过了,所以没有必要重新发明轮子。

import matplotlib.pyplot as plt
from matplotlib import collections, transforms
from matplotlib.colors import colorConverter
import numpy as np

# Make some offsets, doing 4 polygons for simplicity here
xyo = [(0,0), (1,0), (0,1), (1,1)]
# length of hexagon side
hexside = 1
# area of circle circumscribing the hexagon
circ_area = np.pi * hexside ** 2

fig, ax = plt.subplots(1,1)
col = collections.RegularPolyCollection(6, np.radians(90), sizes = (circ_area,),
    offsets=xyo,transOffset=ax.transData)
ax.add_collection(col, autolim=True)
colors = [colorConverter.to_rgba(c) for c in ('r','g','b','c')]
col.set_color(colors)
ax.autoscale_view()
plt.show()

说句实话,我认为你感到困惑是因为“sizes”指定的大小/面积是以点为单位而不是数据坐标。然而,对于你正在做的事情,更简单的方法可能是利用“hexbin”。 - Joe Kington
1个回答

8

如果你在2020年或之后遇到同样的问题,请查看我的hexalattice模块: 它允许在2D中创建具有六边形分布的六边形网格(六边形晶格),可以对六边形空间分布、圆形裁剪和围绕中心槽旋转进行精细控制。

用法和图形输出:

from hexalattice.hexalattice import *
hex_centers, _ = create_hex_grid(nx=10,
                                 ny=10,
                                 do_plot=True)
plt.show()    # import matplotlib.pyplot as plt

10x10六边形网格

安装:

'>> pip install hexalattice'

高级功能

该模块允许堆叠多个网格,围绕其中心任意旋转网格,并且具有对六边形之间间隙的高级控制等功能。

示例:

hex_grid1, h_ax = create_hex_grid(nx=50,
                              ny=50,
                              rotate_deg=0,
                              min_diam=1,
                              crop_circ=20,
                              do_plot=True)
create_hex_grid(nx=50,
                ny=50,
                min_diam=1,
                rotate_deg=5,
                crop_circ=20,
                do_plot=True,
                h_ax=h_ax)

Two round hexagonal lattices create Moire pattern when differ by small rotation


有没有一种简单的方法以某种顺序获取顶点的坐标?(现在只能提取六边形中心)。 - user247534
1
六边形晶格模块并不提供关于顶点的信息,但是计算它们非常简单: 假设六边形处于“尖顶”位置,则可以通过将最大半径加到中心点上来获取上顶点的位置。 有关更多信息,请参阅此优秀博客:https://www.redblobgames.com/grids/hexagons/ - alexkaz

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