python之networkx库小结

备战数模,还是知道多点好。networkx这个库的话,画网络图贼好用。

一、安装

安装的话,跟其他包的安装差不多吧。我用的是anaconda就不用装了。其他的话,就用pip install networkx吧,最好的话,需要装下malplotlib这个库。

二、建立图


 
  
  
  1. import networkx as nx
  2. G=nx.Graph() #创建空的简单图
  3. G=nx.DiGraph() #创建空的简单有向图
  4. G=nx.MultiGraph() #创建空的多图
  5. G=nx.MultiDiGraph() #创建空的有向多图
加点、加边

 
  
  
  1. G.add_node( 1) #加1这个点
  2. G.add_node( 1, 1) #用(1,1)这个坐标加点
  3. G.add_nodes_from([ 2, 3]) #加列表中的点
  4. G.add_edge( 1, 2) #加边,起点是1终点是2
  5. G.add_weight_edge( 1, 2, 3.0) #第三个是权值
  6. G.add_edges_from(list) #添加列表中的边
  7. G.add_weight_edges_from(list)
删除点和边的话

 
  
  
  1. G.remove_node()
  2. G.remove_nodes_from()
  3. G.remove_edge()
  4. G.remove_edges_from()
  5. G.clear()
遍历点和边的话

 
  
  
  1. G.add_nodes_from([ 1, 2, 3])
  2. for n in G.nodes():
  3. print(n)
  4. G.add_edges_from([( 1, 2),( 1, 3)])
  5. for e in G.edges():
  6. print(e)
  7. print(G.degree())
输出:

 
  
  
  1. 1
  2. 2
  3. 3
  4. ( 1, 2)
  5. ( 1, 3)
  6. [( 1, 2), ( 2, 1), ( 3, 1)] #1这个点有两条边连着,2、3只有一条边连着
一些特殊的图的生成:

 
  
  
  1. k_5=nx.complete_graph( 5) #完全图
  2. k_3_3=nx.complete_bipartite_graph( 3, 3) #完全二分图
三、画网络图

这就要用到matplotlib这个库了。

 
  
  
  1. from matplotlib import pyplot as plt
  2. import networkx as nx
  3. G=nx.Graph()
  4. G.add_nodes_from([ 1, 2, 3])
  5. G.add_edges_from([( 1, 2),( 1, 3)])
  6. nx.draw_networkx(G)
  7. plt.show()
输出:



这个应该是最简单的用法了。复杂的图的,还有各种参数的使用只能去networkx的GitHub上看了

四、最短路径的运用

1、无权无向图最短路径


 
  
  
  1. from matplotlib import pyplot as plt
  2. import networkx as nx
  3. G=nx.path_graph( 5)
  4. path=nx.single_source_shortest_path(G, 2)
  5. length=nx.single_source_shortest_path_length(G, 2)
  6. print(path)
  7. print(length)
  8. nx.draw_networkx(G)
  9. plt.show()
输出:

 
  
  
  1. { 2: [ 2], 1: [ 2, 1], 3: [ 2, 3], 0: [ 2, 1, 0], 4: [ 2, 3, 4]}
  2. { 2: 0, 1: 1, 3: 1, 0: 2, 4: 2}

2、有权无向图

以我上个博客为例子吧。


 
  
  
  1. from matplotlib import pyplot as plt
  2. import networkx as nx
  3. nodes=[ 0, 1, 2, 3, 4]
  4. edges=[( 0, 1, 10),( 0, 3, 30),( 0, 4, 100),( 1, 2, 50),( 2, 3, 20),( 2, 4, 10),( 3, 4, 60)]
  5. G=nx.Graph()
  6. G.add_nodes_from(nodes)
  7. G.add_weighted_edges_from(edges)
  8. path=nx.single_source_dijkstra_path(G, 4)
  9. length=nx.single_source_dijkstra_path_length(G, 4)
  10. print(path)
  11. print(length)
  12. nx.draw_networkx(G)
  13. plt.show()
输出:

 
  
  
  1. { 4: [ 4], 0: [ 4, 2, 3, 0], 2: [ 4, 2], 3: [ 4, 2, 3], 1: [ 4, 2, 1]}
  2. { 4: 0, 2: 10, 3: 30, 1: 60, 0: 60}

可以好好跟我的上个博客对比一下。

五、参考

https://networkx.github.io/documentation/networkx-1.9

**转自**:https://blog.csdn.net/your_answer/article/details/79189660

猜你喜欢

转载自blog.csdn.net/weixin_44010756/article/details/107349387
今日推荐