python - Networkx 不同层的六方晶格

标签 python networkx graph-theory

如何扩展此代码以包含不同数量的六边形层? 我需要一个给定层数 m 的六方晶格图。 m=1 表示 1 个边长为 1、中心位于原点的正六边形,m=2 时在第一个正六边形周围添加 6 个正六边形,m=3 时添加第三层六边形,依此类推。

import networkx as nx
import matplotlib.pyplot as plt
G = nx.hexagonal_lattice_graph(m=2,n=3, periodic=False, with_positions=True, 
                               create_using=None)
pos = nx.get_node_attributes(G, 'pos')
nx.draw(G, pos=pos, with_labels=True)
plt.show()

最佳答案

一个有趣的问题!我花了比我预期更长的时间。基本上,函数hexagonal_lattice_graph() 生成一个m x n 矩形 六边形网格。因此,任务是首先绘制一个大网格,然后删除最外层之外的节点。 我使用距离来决定保留哪些节点以及删除哪些节点。这更加棘手,因为奇数和偶数 m 的行为略有不同。所以中心坐标必须仔细计算。

import networkx as nx
import matplotlib.pyplot as plt


def node_dist(x,y, cx, cy):
    """Distance of each node from the center of the innermost layer"""
    return abs(cx-x) + abs(cy-y)


def remove_unwanted_nodes(G, m):
    """Remove all the nodes that don't belong to an m-layer hexagonal ring."""
    
    #Compute center of all the hexagonal rings as cx, cy
    cx, cy = m-0.5, 2*m -(m%2) #odd is 2m-1, even is 2m
    
    #in essence, we are converting from a rectangular grid to a hexagonal ring... based on distance.
    unwanted = []
    for n in G.nodes:    
        x,y = n
        #keep short distance nodes, add far away nodes to the list called unwanted
        if node_dist(x,y, cx, cy) > 2*m:
            unwanted.append(n)

    #now we are removing the nodes from the Graph
    for n in unwanted:
        G.remove_node(n)
        
    return G



##################
m = 4 #change m here. 1 = 1 layer, single hexagon.
G = nx.hexagonal_lattice_graph(2*m-1,2*m-1, periodic=False, 
                               with_positions=True, 
                               create_using=None)
pos = nx.get_node_attributes(G, 'pos')
G = remove_unwanted_nodes(G, m)

#render the result
plt.figure(figsize=(9,9)) 
nx.draw(G, pos=pos, with_labels=True)
plt.axis('scaled')
plt.show()

对于 m=3 产生以下结果: Hex Ring for m =3

对于 m=4:

Hexagonal Ring for m=4

欢迎来到SO!希望上述解决方案是清晰的并帮助您继续前进。

关于python - Networkx 不同层的六方晶格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64222103/

相关文章:

java - 当你有小段时,如何显示每条可能采取的路径?

python - 在图中获取循环的算法?

python - LSTM Keras 网络的恒定输出和预测语法

Python Pandas - 创建包含节点对和边强度的 DataFrame

python - 使用链接矩阵和 networkx 绘制有向图

python - 如何添加自定义函数来计算图中的边权重?

graph - 有没有办法将 jung 连接到数据库的保存/写入?

Python 多处理 : What's the difference between map and imap?

python - 如何在Python中以安全的方式创建目录

python - 如何将 QPlainTextEdit 向右对齐?