有时候graph建好后,我们并不清楚该graph内节点、边的信息,需要调用函数去查看Graph的信息。
目录
1、查看graph内节点,边的
数量
数量
# 生成graph
G = nx.path_graph(8) # 生成一个8个点的图
nx.draw(G, with_labels=True) # 画图
plt.axis('on')
plt.xticks([])
plt.yticks([])
plt.show() # 显示图
# 查看节点和边的情况
print('number of nodes',G.number_of_nodes())
# number of nodes 8
print('number of edges',G.number_of_edges())
# number of edges 7
这里axis(‘on’)的意思是:
axis()
- 函数功能:plt.axis() 是获取或设置某些轴属性的便捷方法
- 第一种使用方法: plt.axis([xmin, xmax, ymin, ymax])
- xmin:x轴的最小范围值
- xmax:x轴的最大范围值
- ymin:y轴的最小范围值
- ymax:y轴的最大范围值
- 第二种使用方法: plt.axis(str)
- “on”:打开轴线和标签
- “off”:关闭轴线和标签
- “scaled”:设置相等的缩放比例
- “tight”:设置限制大小足以显示所有数据
- “auto”:自动缩放(带数据的填充框)
2、查看graph中的点,边
# 输出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)]
3、查看某些节点的度
# 查看节点2和3的度
print('degree of some nodes', G.degree([2, 3]))
# degree of some nodes [(2, 2), (3, 2)]
4、查看节点&边信息
# 设置一些节点信息
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])
# imformation of one nodes {'room': 714, 'color': 'b'}
print('imformation of all nodes', G.nodes.data())
# imformation of all nodes [(0, {}), (1, {'room': 714, 'color': 'b'}), (2, {}), (3, {}), (4, {}), (5, {}), (6, {}), (7, {})]
print('imformation of all nodes', G.edges.data()) #边不支持[x]这样的下标访问
# imformation of all nodes [(0, 1, {}), (1, 2, {'weight': 4.7, 'color': 'blue'}), (2, 3, {}), (3, 4, {}), (4, 5, {}), (5, 6, {}), (6,7, {})]
5、遍历一个有权图
# 定义一个有权无向图
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))
# way1-(1, 2, 0.125)
# way1-(2, 1, 0.125)
# way1-(3, 4, 0.375)
# way1-(4, 3, 0.375)
# 遍历所有边
for (u, v, wt) in FG.edges.data('weight'):
#权重小于0.5的输出
if wt < 0.5:
print('way2-(%d, %d, %.3f)' % (u, v, wt))
# way2-(1, 2, 0.125)
# way2-(3, 4, 0.375)
图的邻接矩阵遍历
# 遍历邻接矩阵
for n, nbrs in FG.adj.items():
print(n, nbrs)
# 1 {2: {'weight': 0.125}, 3: {'weight': 0.75}}
# 2 {1: {'weight': 0.125}, 4: {'weight': 1.2}}
# 3 {1: {'weight': 0.75}, 4: {'weight': 0.375}}
# 4 {2: {'weight': 1.2}, 3: {'weight': 0.375}}
for n, nbrs in FG.adj.items():
for nbr, eattr in nbrs.items():
print(nbr, eattr)
# 2 {'weight': 0.125}
# 3 {'weight': 0.75}
# 1 {'weight': 0.125}
# 4 {'weight': 1.2}
# 1 {'weight': 0.75}
# 4 {'weight': 0.375}
# 2 {'weight': 1.2}
# 3 {'weight': 0.375}
# 遍历所有边
for (u, v, wt) in FG.edges.data('weight'):
print (u, v, wt)
# 1 2 0.125
# 1 3 0.75
# 2 4 1.2
# 3 4 0.375
参考:
完整的教程信息查看第一个部分(1),讲的很好啊!!!
版权声明:本文为weixin_31866177原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。