Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

python - map a hexagonal grid in matplotlib

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Hexagonal grid of 10x10 hexagons

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)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...