NetworkX系列教程(5)-查看graph的信息

有时候graph建好后,我们并不清除该graph内节点的,边的信息,这就需要调用函数去查看了.

注意: 如果代码出现找不库,请返回第一个教程,把库文件导入.

查看Graph的信息

查看graph内节点,边的数量

1
2
3
4
5
6
7
8
9
10
11
#生成graph
G=nx.path_graph(8)
nx.draw(G,with_labels=True)
plt.axis('on')
plt.xticks([])
plt.yticks([])
plt.show()

#查看节点和边的情况
print('number of nodes',G.number_of_nodes())
print('number of edges',G.number_of_edges())

enter description here

输出:

number of nodes 8
number of edges 7

查看graph中的点,边

1
2
3
#输出graph所有的点和边
print('all nodes of Graph',G.nodes())
print('all edges of Graph',G.edges())

输出:

all nodes of Graph [0, 1, 2, 3, 4, 5, 6, 7]
all edges of Graph [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]

查看某些节点的度

1
2
#查看节点2和3的度
print('degree of some nodes',G.degree([2, 3]))

输出:

degree of some nodes [(2, 2), (3, 2)]

查看节点&边信息

1
2
3
4
5
6
7
8
9
10
11
#设置一些节点信息
G.nodes[1]['room'] = 714
G.nodes[1]['color'] = 'b'
#设置一些边信息
G[1][2]['weight'] = 4.7
G[1][2]['color'] = "blue"

print('imformation of one nodes',G.nodes[1])
print('imformation of all nodes',G.nodes.data())

print('imformation of all nodes',G.edges.data()) #边不支持[x]这样的下标访问

输出:

imformation of one nodes {'room': 714, 'color': 'b'}
imformation of all nodes [(0, {}), (1, {'room': 714, 'color': 'b'}), (2, {}), (3, {}), (4, {}), (5, {}), (6, {}), (7, {})]
imformation of all nodes [(0, 1, {}), (1, 2, {'weight': 4.7, 'color': 'blue'}), (2, 3, {}), (3, 4, {}), (4, 5, {}), (5, 6, {}), (6,7, {})]

遍历一个有权图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#定义一个有权无向图
FG = nx.Graph()
FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)])

#遍历邻接矩阵
for n, nbrs in FG.adj.items():
for nbr, eattr in nbrs.items():
wt = eattr['weight']
#权重小于0.5的输出
if wt < 0.5:
print('way1-(%d, %d, %.3f)' % (n, nbr, wt))

#遍历所有边
for (u, v, wt) in FG.edges.data('weight'):
#权重小于0.5的输出
if wt < 0.5:
print('way2-(%d, %d, %.3f)' % (u, v, wt))

输出:

way1-(1, 2, 0.125)
way1-(2, 1, 0.125)
way1-(3, 4, 0.375)
way1-(4, 3, 0.375)
way2-(1, 2, 0.125)
way2-(3, 4, 0.375)