网络分析库—NetworkX
程序员文章站
2022-04-25 13:25:41
...
NetworkX是一个用Python语言开发的图论与复杂网络建模工具,内置了常用的图与复杂网络分析算法,可以方便的进行复杂网络数据分析、仿真建模等工作。networkx支持创建简单无向图、有向图和多重图(multigraph);内置许多标准的图论算法,节点可为任意数据;支持任意的边值维度,功能丰富,简单易用。本次只学习其中部分内容。
import networkx as nx
print(nx)
<module 'networkx' from 'C:\\Users\\user\\Anaconda3\\lib\\site-packages\\networkx\\__init__.py'>
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_node(1)
G.add_edge(2,3)
print(G.nodes())
[1, 2, 3]
print(G.edges())
[(2, 3)]
print(G.number_of_edges())
1
nx.draw(G)
plt.show()
plt.savefig('node.png')
<matplotlib.figure.Figure at 0x9617320>
GG = nx.DiGraph()
GG.add_node(1)
GG.add_node(2)
GG.add_nodes_from([3,4,5,6])
GG.add_cycle([1,2,3,4])
GG.add_edge(3,5)
nx.draw(GG)
#plt.savefig("you.png")
#plt.show()
GGG = GG.to_undirected()
nx.draw(GGG)
注:有向图和无向图可以互相转换,使用函数:
- to_undirected()
- to_directed()
shortest_path, 结合osmnx:最短路径及显示
import networkx as nx
import osmnx as ox
import matplotlib.pylab as plt
lp = (39.9055, 116.3912)#点
G = ox.graph_from_point(lp, distance = 1500, distance_type = 'network',
network_type = 'walk')
orign_point = (39.9055, 116.3912)
destination_point = (39.9255, 114.4112)
orign_node = ox.get_nearest_node(G, orign_point)
destination_node = ox.get_nearest_node(G, destination_point)
orign_node, destination_node
(3629758785, 342803803)
route = nx.shortest_path(G, orign_node, destination_node, weight = 'length')
str(route)
'[3629758785, 4710347260, 4710347262, 4718004204, 5115805582, 5375025713, 5375025714, 5375025719, 5375025720, 5375031121, 5375031122, 342803803]'
fig, nx = ox.plot_graph_route(G, route, origin_point=orign_point, destination_point=destination_point)
nodes/edges的提取:结合osmnx/networks
按照查询的资料显示,nodes/edges的,G.nodes()/G.edges()是来自于networkx。
但是,在osmnx的文档中,有使用networkx的用例。可能networkx也可以使用G = ox.graph()....
所以,做了如下的例子。其中,G来自于osmnx,而G.nodes(data = True)是networkx的语法。
G= ox.load_graphml(r'C:\Users\user\project\gz_simple.graphml')#读取路网数据
data_nodes = list(G.nodes(data = True))#True,输出dict,默认False,输出第一列
具体可以查看,参照:
https://www.cnblogs.com/kaituorensheng/p/5423131.html,
https://networkx.github.io/documentation/networkx-1.9/download.html
https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.Graph.edges.html?highlight=edges#networkx.Graph.edges