Hexagonal lattice in different layers by networkx(用Networkx实现不同层数的六方晶格)
本文介绍了用Networkx实现不同层数的六方晶格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何扩展此代码,以包括不同数量的六角形层? 我需要一个给定层数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生成以下内容:
对于m=4:
欢迎来到So!希望上面的解决方案是明确的,并帮助您继续前进。
这篇关于用Networkx实现不同层数的六方晶格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:用Networkx实现不同层数的六方晶格
基础教程推荐
猜你喜欢
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
