gpt4 book ai didi

python - Networkx 随机几何图限制节点在半径 r 内

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:46 24 4
gpt4 key购买 nike

所以我有来自 networkx 示例的这段代码,但我试图弄清楚如何将节点限制在半径“r”内,以便在圆的边界内绘制随机几何图形。我知道我会如何在逻辑上做到这一点,但我对一切的运作方式有点困惑,并且一直在尝试自己解决问题,但到目前为止还没有解决方案。感谢您的帮助!

import networkx as nx
import matplotlib.pyplot as plt

G = nx.random_geometric_graph(1000,0.1)

# position is stored as node attribute data for random_geometric_graph
pos = nx.get_node_attributes(G,'pos')

# find node near center (0.5,0.5)
dmin =1
ncenter =0
for n in pos:
x,y = pos[n]
d = (x-0.5)**2+(y-0.5)**2
if d<dmin:
ncenter = n
dmin = d

# color by path length from node near center
p = nx.single_source_shortest_path_length(G,ncenter)

plt.figure(figsize=(8,8))
#node_color=p.values()
nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4)
nx.draw_networkx_nodes(G,pos,nodelist=p.keys(),
node_size=80,
node_color='#0F1C95',
cmap=plt.cm.Reds_r)

plt.xlim(-0.05,1.05)
plt.ylim(-0.05,1.05)
plt.axis('off')
plt.savefig('random_geometric_graph.png')
plt.show()

最佳答案

你可以使用像这样的字典理解

p = {node:length for node, length in nx.single_source_shortest_path_length(G,ncenter).items()
if length < 5}

将 dict 限制为与 ncenter 的距离为 < 5 的那些节点。

对于 Python2.6 或更早的版本,你可以使用

p = dict((node, length) for node, length in nx.single_source_shortest_path_length(G,ncenter).items()
if length < 5)

你也可以替换

dmin =1
ncenter =0
for n in pos:
x,y = pos[n]
d = (x-0.5)**2+(y-0.5)**2
if d<dmin:
ncenter = n
dmin = d

用单线:

ncenter, _ = min(pos.items(), key = lambda (node, (x,y)): (x-0.5)**2+(y-0.5)**2)

要仅绘制与 ncenter 的距离为 < 5 的那些节点,请定义子图:

H = G.subgraph(p.keys())    
nx.draw_networkx_edges(H, pos, alpha = 0.4)
nx.draw_networkx_nodes(H, pos, node_size = 80, node_color = node_color,
cmap = plt.get_cmap('Reds_r'))

import networkx as nx
import matplotlib.pyplot as plt
G = nx.random_geometric_graph(1000, 0.1)

# position is stored as node attribute data for random_geometric_graph
pos = nx.get_node_attributes(G, 'pos')

# find node near center (0.5,0.5)
ncenter, _ = min(pos.items(), key = lambda (node, (x, y)): (x-0.5)**2+(y-0.5)**2)

# color by path length from node near center
p = {node:length
for node, length in nx.single_source_shortest_path_length(G, ncenter).items()
if length < 5}

plt.figure(figsize = (8, 8))
node_color = p.values()
H = G.subgraph(p.keys())
nx.draw_networkx_edges(H, pos, alpha = 0.4)
nx.draw_networkx_nodes(H, pos, node_size = 80, node_color = node_color,
cmap = plt.get_cmap('Reds_r'))

plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
plt.axis('off')
plt.savefig('random_geometric_graph.png')
plt.show()

enter image description here

关于python - Networkx 随机几何图限制节点在半径 r 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13792046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com