在 matplotlib 中映射六边形网格
问题描述
我想画一个带有六边形网格的图形.最终结果应该看起来像一个蜂窝.但是,我无法使用 matplotlib.collections.RegularPolyCollection 正确调整六边形的大小.谁能看到我做错了什么,或提供另一种解决方案.我想这已经完成了,所以我不需要重新发明轮子.
import matplotlib.pyplot as plt从 matplotlib 导入集合,转换从 matplotlib.colors 导入颜色转换器将 numpy 导入为 np# 做一些偏移,这里为了简单起见做 4 个多边形xyo = [(0,0), (1,0), (0,1), (1,1)]# 六边形边长六边形 = 1# 六边形外接圆的面积circ_area = np.pi * hexside ** 2无花果,斧头 = plt.subplots(1,1)col = collections.RegularPolyCollection(6, np.radians(90), sizes = (circ_area,),偏移量=xyo,transOffset=ax.transData)ax.add_collection(col, autolim=True)颜色 = [colorConverter.to_rgba(c) for c in ('r','g','b','c')]col.set_color(颜色)ax.autoscale_view()plt.show()
解决方案 谁在 2020+ 年遇到同样的问题,请查看我的
安装:
'>>点安装 hexalattice'
高级功能
该模块允许堆叠少量网格、围绕其中心任意旋转网格、对六边形之间的间隙进行高级控制等.
例子:
hex_grid1, h_ax = create_hex_grid(nx=50,ny=50,旋转度= 0,min_diam=1,crop_circ=20,do_plot=真)create_hex_grid(nx=50,ny=50,min_diam=1,旋转度=5,crop_circ=20,do_plot=真,h_ax=h_ax)
I'm wanting to draw a figure with a hexagonal grid. The end result should look like a honeycomb. However, I'm having trouble getting my hexagons sized correctly using matplotlib.collections.RegularPolyCollection. Can anyone see what I am doing wrong, or offer another solution. I imagine this has been done before, so no need for me to reinvent the wheel.
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()
解决方案
Whoever struggles with the same issue in 2020+, check out my hexalattice module: It allows to create hexagonal grids (hexagonal lattices) in 2D with fine control over spatial distribution of the hexagons, circular clop of the lattice and rotations around the central slot.
Usage and graphical output:
from hexalattice.hexalattice import *
hex_centers, _ = create_hex_grid(nx=10,
ny=10,
do_plot=True)
plt.show() # import matplotlib.pyplot as plt
Installation:
'>> pip install hexalattice'
Advanced features
The module allows stacking of few grids, arbitrary grid rotation around its center, advanced control over gaps between the hexagons etc.
Example:
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)
相关文章