如何解决网络x
如何扩展此代码以包含不同数量的六角形层? 我需要一个给定层数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
六角形的 rectangular 网格。因此,任务是首先绘制一个大网格,然后删除最外层外部的节点。
我使用距离来确定保留哪些节点,以及删除哪些节点。这更加棘手,因为奇数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,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()
的行为略有不同。因此,必须仔细计算中心坐标。
data/marvel/thor
并且对于m = 4:
欢迎您!希望上面的解决方案很清楚,并能帮助您前进。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。