在matplotlib中映射一个六角形网格 [英] map a hexagonal grid in matplotlib

查看:280
本文介绍了在matplotlib中映射一个六角形网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一个带有六边形网格的图形.最终结果应看起来像蜂窝.但是,我无法使用matplotlib.collections.RegularPolyCollection正确设置六边形的大小.谁能看到我在做什么错,或提供其他解决方案.我想这是以前做过的,所以不需要我重新发明轮子.

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()

推荐答案

如果在2020年以上遇到同样的问题,请查看我的

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.

用法和图形输出:

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

安装:

'>> pip install hexalattice'

高级功能

该模块允许堆叠少量网格,围绕其中心的任意网格旋转,高级控制六边形之间的间隙等.

The module allows stacking of few grids, arbitrary grid rotation around its center, advanced control over gaps between the hexagons etc.

示例:

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)

这篇关于在matplotlib中映射一个六角形网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆