【问题标题】:Python, NetworkX hexagonal lattice problem - how to create a perfect lattice?Python、NetworkX六角点阵问题——如何创建完美点阵?
【发布时间】:2020-08-18 17:52:16
【问题描述】:

所以我试图在 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 个六边形?

谢谢!

【问题讨论】:

  • 我建议将图像嵌入问题中。
  • 答案是肯定的,您需要在nx.draw() 中使用pos 参数来定义顶点的确切位置。

标签: python networkx physics lattice


【解决方案1】:

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

with_positions (bool (default: 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多