Python,NetworkX六角格问题-如何创建完美的格?

问题描述

因此,我尝试使用Python中的NetworkX生成六边形格子。使用代码后:

G = nx.hexagonal_lattice_graph(m=2,n=2,periodic=False,with_positions=True,create_using=None)
plt.subplot(111)
nx.draw(G,with_labels=True,font_weight='bold')
plt.show()

我得到一个看起来像这样的六角形格子: lattice

如您所见,此格子由不规则的六边形形成,每次运行代码时,形状都会发生变化。是否有一种方法可以使用NetworkX(即this,但只有X个六边形)生成完美的六边形格子?

谢谢!

解决方法

您需要在with_postion函数中使用hexagonal_lattic_graph属性,并将其设置为True。这会将节点的位置存储在图pos本身内部名为G的属性中。您可以从文档here中了解更多信息:

with_positions(布尔型(默认值:True)) –将每个节点的坐标存储在图形节点属性“ pos”中。坐标提供了一个六边形的垂直列,偏移的六边形可以交织并覆盖平面。周期位置以非线性方式垂直移动节点,因此边缘不会重叠太多。

因此,您只需要从图形本身中提取位置,就像这样:

pos = nx.get_node_attributes(G,'pos')

然后,在绘制图形时以pos传递

import networkx as nx
import matplotlib.pyplot as plt

# create the graph and set with_positions=True
G = nx.hexagonal_lattice_graph(m=2,n=2,periodic=False,with_positions=True,create_using=None)
plt.subplot(111)

# Extract the positions
pos = nx.get_node_attributes(G,'pos')

# Pass the positions while drawing
nx.draw(G,pos=pos,with_labels=True,font_weight='bold')
plt.show()

Hexagonal lattices

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...