赞
踩
本文主要介绍Networkx的使用方法和一些简单的应用案例,使用方法主要会介绍创建图、图的基本操作等;应用案例不仅会介绍如何生成无向图、有向图等,还会介绍Networkx在计算机网络、数据中心网络等网络中的简单应用案例。
在cmd或者shell中输入命令:
pip install networkx
如果使用python中的.ipynb的话也可以:
%pip install networkx
import networkx as nx
import matplotlib.pyplot as plt
print(nx.__version__)
G = nx.Graph() # 无向图
G = nx.DiGraph() # 有向图
G = nx.MultiGraph() # 多重无向图
G = nx.MultiDigraph() # 多重有向图
G.clear() # 清空图
在添加边的时候,如果使用了未添加的节点,则会自动添加节点。另外单纯添加节点的方法是:
# 添加节点
G.add_node(1)
G.add_nodes_from([2, 3, 4])
G.add_edge(1, 2) # default edge data=1
G.add_edge(2, 3, weight=0.9) # specify edge data
# 如果是边有许多的权,比如有长度和宽度的属性,那么:
G.add_edge(n1, n2, length=2, width=3)
elist = [(1, 2), (2, 3), (1, 4), (4, 2)]
G.add_edges_from(elist)
elist = [('a', 'b', 5.0), ('b', 'c', 3.0), ('a', 'c', 1.0), ('c', 'd', 7.3)]
G.add_weighted_edges_from(elist)
# 如果给结点的名称是其它符号,想离散化成从x开始的数字标记,那么:
G = nx.convert_node_labels_to_integers(G, first_label=x)
nx.info(G) # 图信息的概览 G.number_of_nodes() G.number_of_edges() # 获取和节点idx连接的边的attr属性之和 G.in_degree(idx, weight='attr') # 如果想知道某个结点相连的某个边权之和: DG.degree(nodeIdx, weight='weightName') # 获取结点或者边的属性集合,返回的是元组的列表 G.nodes.data('attrName') G.edges.data('attrName') # 获取n1 n2的边的length权重,那么: G[n1][n2]['length'] # 如果是有重边的图,选择n1,n2第一条边的length权重,则: G[n1][n2][0]['length'] # 获取n1结点的所有邻居 nx.all_neighbors(G, n1) # 判断图中n1到n2是否存在路径 nx.has_path(G, n1, n2) # 根据一个结点的list,获取子图 subG = nx.subgraph(G, nodeList)
# 最简单的绘制 import matplotlib.pyplot as plt nx.draw(G) plt.show() # 设置其他相关参数 nx.draw(G, with_labels=True, pos = nx.sprint_layout(G), node_color=color_list, edge_color='k', node_size=100, node_shape='o', linewidths=2, width=1.0, alpha=0.55, style='solid', font_size=9, font_color='k' )
G = nx.karate_club_graph()
plt.figure(figsize =(10, 8))
nx.draw_networkx(G, with_labels = True)
# 创建一个无向图 G = nx.Graph() # 添加节点 G.add_node(1) G.add_nodes_from([2, 3, 4]) # 添加边 G.add_edge(1, 2) G.add_edges_from([(1, 3), (2, 4), (3, 4)]) # 绘制图形 nx.draw(G, with_labels=True, font_weight='bold') plt.show() # 输出图的基本信息 print("图中的节点:", G.nodes()) print("图中的边:", G.edges()) print("节点 1 的邻居:", list(G.neighbors(1)))
# 创建一个有向图 DiG = nx.DiGraph() # 添加节点 DiG.add_node(1) DiG.add_nodes_from([2, 3, 4]) # 添加有向边 DiG.add_edge(1, 2) DiG.add_edges_from([(1, 3), (2, 4), (3, 4)]) # 绘制图形 nx.draw(DiG, with_labels=True, font_weight='bold', arrowsize=20, node_size=700) plt.show() # 输出有向图的基本信息 print("有向图中的节点:", DiG.nodes()) print("有向图中的有向边:", DiG.edges()) print("节点 1 的出度:", DiG.out_degree(1)) print("节点 1 的入度:", DiG.in_degree(1))
# 创建一个有向图表示网络拓扑 G = nx.DiGraph() # 添加节点和边 G.add_nodes_from(["Router1", "Router2", "Switch1", "Computer1"]) G.add_edges_from([("Router1", "Router2"), ("Router1", "Switch1"), ("Switch1", "Computer1")]) # 绘制网络拓扑 nx.draw(G, with_labels=True, font_weight='bold', arrowsize=20, node_size=700) plt.show() # 计算节点度 degrees = dict(G.degree()) print("节点度:", degrees) # 计算聚类系数 clustering_coefficient = nx.clustering(G) print("聚类系数:", clustering_coefficient) # 计算最短路径 shortest_path = nx.shortest_path(G, source="Router1", target="Computer1") print("最短路径:", shortest_path) # 绘制带权重的有向图 nx.draw(G, with_labels=True, font_weight='bold', arrowsize=20, node_size=700, connectionstyle='arc3,rad=0.1') plt.show() # 查找所有最短路径 all_shortest_paths = list(nx.all_shortest_paths(G, source="Router1", target="Computer1")) print("所有最短路径:", all_shortest_paths) # 计算路径长度 path_length = nx.shortest_path_length(G, source="Router1", target="Computer1") print("最短路径长度:", path_length)
import networkx as nx import matplotlib.pyplot as plt import random # 创建一个有向图表示网络拓扑 network_topology = nx.DiGraph() # 添加节点和边 network_topology.add_nodes_from(["Router1", "Router2", "Switch1", "Link1"]) network_topology.add_edges_from([("Router1", "Switch1"), ("Router2", "Switch1"), ("Switch1", "Link1")]) # 添加边属性表示流量和权重 network_topology["Switch1"]["Link1"]["traffic"] = 0 network_topology["Switch1"]["Link1"]["threshold"] = 50 network_topology["Switch1"]["Link1"]["weight"] = 1.0 # 模拟拥塞控制算法 def congestion_control(network, threshold): for edge in network.edges(data=True): # 检查键是否存在,如果不存在则初始化 if "traffic" not in edge[2]: edge[2]["traffic"] = 0 edge[2]["traffic"] += random.randint(0, 20) # 模拟随机流量增加 if edge[2]["traffic"] > threshold: # 执行拥塞控制动作 edge[2]["weight"] = 2.0 # 增加拥塞链路的权重 else: edge[2]["weight"] = 1.0 # 恢复非拥塞链路的权重 # 模拟多个时间步的拥塞控制 for i in range(5): congestion_control(network_topology, threshold=network_topology["Switch1"]["Link1"]["threshold"]) print(f"时间步 {i + 1} - Link1 流量:{network_topology['Switch1']['Link1']['traffic']}") # 绘制带权重的有向图 edge_weights = [edge[2]["weight"] for edge in network_topology.edges(data=True)] nx.draw(network_topology, with_labels=True, font_weight='bold', arrowsize=20, node_size=700, edge_color=edge_weights, cmap=plt.cm.Blues) plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。