1 基礎教程
常用網站:
NetworkX官方介紹:
NetworkX (NX) is a Python package for the creation, manipulation, and
study of the structure, dynamics, and functions of complex networks.
<https://networkx.lanl.gov/>
Just write in Python
>>> import networkx as nx
>>> G=nx.Graph()
>>> G.add_edge(1,2)
>>> G.add_node(42)
>>> print(sorted(G.nodes()))
[1, 2, 42]
>>> print(sorted(G.edges()))
[(1, 2)]
- 用來處理無向圖、有向圖、多重圖的 Python 數據結構
- 包含許多標准的圖算法
- 包括網絡結構和分析方法
- 用於產生經典圖、隨機圖和綜合網絡
- 節點可以是任何事物(如 text, images, XML records)
- 邊能保存任意起算值(如 weights, time-series)
- 從 Python 獲得的額外優勢:快速原型開發方法,容易學,支持多平台。
比如,可以直接求出最短路徑:
import networkx as nx
G = nx.Graph()
G.add_edge('A', 'B', weight=4)
G.add_edge('B', 'D', weight=2)
G.add_edge('A', 'C', weight=3)
G.add_edge('C', 'D', weight=4)
nx.shortest_path(G, 'A', 'D', weight='weight')
['A', 'B', 'D']
下面開始打開學習的大門。
1.1 創建圖
創建圖很簡單:
import networkx as nx
G=nx.Graph() # 一個沒有邊和節點的空圖
Graph 是節點(向量)與確定的節點對(稱作邊、鏈接(links)等)組成的集合。在 Networkx 中,節點可以是任何可哈希的[1]對象,如文本字符串、圖片、XML對象、其他圖,自定義的節點對象等。
注意:Python 的 None 對象不應該用作節點。
1.2 節點
Neatworkx 包含很多圖生成器函數和工具,可用來以多種格式來讀寫圖。
- 一次增加一個節點:
G.add_node(1) - 用序列增加一系列的節點:
G.add_nodes_from([2,3]) - 增加任意的可迭代的結點容器(序列、集合、圖、文件等)
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3])
# type(H) networkx.classes.graph.Graph,H 是一個有 10 個節點的鏈狀圖,即有 n 個節點 n-1 條邊的連通圖
H = nx.path_graph(10)
G.add_nodes_from(H) # 這是將 H 中的許多結點作為 G 的節點
G.add_node(H) # 這是將 H 作為 G 中的一個節點
G.nodes # 查看結點
輸出:
NodeView((1, 2, 3, 0, 4, 5, 6, 7, 8, 9, <networkx.classes.graph.Graph object at 0x0000026E0347B548>))
1.3 邊
#G能夠一次增加一條邊
G.add_edge(1,2) #只能增加邊,有屬性,除非指定屬性名和值“屬性名=值”
e=(2,3)
G.add_edge(*e) #注意! G.add_edge(e)會報錯!G.add_edge(e)
#用序列增加一系列結點
G.add_edges_from([(1,2),(1,3)])
#增加 ebunch邊。ebunch:包含邊元組的容器,比如序列、迭代器、文件等
#這個元組可以是2維元組或 三維元組 (node1,node2,an_edge_attribute_dictionary),an_edge_attribute_dictionary比如:
#{‘weight’:3.1415}
G.add_edges_from(H.edges())
1.4 刪除
#G.remove_node(),G.remove_nodes_from()
#G.remove_edge(),G.remove_edges_from()
G.remove_node(H) #刪除不存在的東西會報錯
#移除所有的節點和邊
G.clear()
G.add_edges_from([(1,2),(1,3)])
G.add_node(1)
G.add_edge(1,2)
G.add_node("spam")
G.add_nodes_from("spam") # adds 4 nodes: 's', 'p', 'a', 'm'
G.add_edge(3, 'm')
G.number_of_edges() # 邊的個數
G.number_of_nodes() # 節點的個數
1.5 圖的屬性
圖有四個基本屬性:G.nodes, G.edges, G.degree, G.adj,分別表示節點集、邊集、度、鄰域。
print(G.nodes, G.edges) # 查看節點和邊
G.adj[1] # 查看鄰域
G.degree[1] # 查看節點的度
更多精彩:
>>> G = nx.path_graph(3)
>>> list(G.nodes)
[0, 1, 2]
>>> list(G)
[0, 1, 2]
>>> G.add_node(1, time='5pm')
>>> G.nodes[0]['foo'] = 'bar'
>>> list(G.nodes(data=True))
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes.data())
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data='foo'))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes.data('foo'))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time'))
[(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes.data('time'))
[(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data='time', default='Not Available'))
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
>>> list(G.nodes.data('time', default='Not Available'))
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
>>> G = nx.Graph()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict(G.nodes(data='weight', default=1))
{0: 1, 1: 2, 2: 3}
2 無向圖
前面介紹的圖就是無向圖,即:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph() #建立一個空的無向圖G
G.add_node(1) #添加一個節點1
G.add_edge(2,3) #添加一條邊2-3(隱含着添加了兩個節點2、3)
G.add_edge(3,2) #對於無向圖,邊3-2與邊2-3被認為是一條邊
print ("nodes:", G.nodes()) #輸出全部的節點: [1, 2, 3]
print ("edges:", G.edges()) #輸出全部的邊:[(2, 3)]
print ("number of edges:", G.number_of_edges()) #輸出邊的數量:1
nx.draw(G)
plt.savefig("wuxiangtu.png")
plt.show()
nodes: [1, 2, 3]
edges: [(2, 3)]
number of edges: 1

3 有向圖
#-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node(1)
G.add_node(2) #加點
G.add_nodes_from([3,4,5,6]) #加點集合
G.add_edges_from(zip(range(1, 5), [2, 3, 4, 1])) # 加環
G.add_edge(1,3)
G.add_edges_from([(3,5),(3,6),(6,7)]) #加邊集合
nx.draw(G)
plt.savefig("有向圖.png")
plt.show()

注:使用函數 Graph.to_undirected() 與 Graph.to_directed() 有向圖和無向圖可以互相轉換。
# 例子中把有向圖轉化為無向圖
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.add_nodes_from([3,4,5,6])
G.add_edges_from(zip(range(1, 5), [2, 3, 4, 1])) # 加環
G.add_edge(1,3)
G.add_edges_from([(3,5),(3,6),(6,7)])
G = G.to_undirected()
nx.draw(G)
plt.savefig("wuxiangtu.png")
plt.show()

#-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
road_nodes = {'a': 1, 'b': 2, 'c': 3}
#road_nodes = {'a':{1:1}, 'b':{2:2}, 'c':{3:3}}
road_edges = [('a', 'b'), ('b', 'c')]
G.add_nodes_from(road_nodes.items())
G.add_edges_from(road_edges)
nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()

#-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
#road_nodes = {'a': 1, 'b': 2, 'c': 3}
road_nodes = {'a':{1:1}, 'b':{2:2}, 'c':{3:3}}
road_edges = [('a', 'b'), ('b', 'c')]
G.add_nodes_from(road_nodes.items())
G.add_edges_from(road_edges)
nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()

4 加權圖
有向圖和無向圖都可以給邊賦予權重,用到的方法是add_weighted_edges_from,它接受1個或多個三元組[u,v,w]作為參數,
其中u是起點,v是終點,w是權重
#!-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph() #建立一個空的無向圖G
G.add_edge(2,3) #添加一條邊2-3(隱含着添加了兩個節點2、3)
G.add_weighted_edges_from([(3, 4, 3.5),(3, 5, 7.0)]) #對於無向圖,邊3-2與邊2-3被認為是一條邊
print (G.get_edge_data(2, 3))
print (G.get_edge_data(3, 4))
print (G.get_edge_data(3, 5))
nx.draw(G)
plt.savefig("wuxiangtu.png")
plt.show()
{}
{'weight': 3.5}
{'weight': 7.0}

import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
5 經典圖論算法計算
計算1:求無向圖的任意兩點間的最短路徑
# -*- coding: cp936 -*-
import networkx as nx
import matplotlib.pyplot as plt
#計算1:求無向圖的任意兩點間的最短路徑
G = nx.Graph()
G.add_edges_from([(1,2),(1,3),(1,4),(1,5),(4,5),(4,6),(5,6)])
path = nx.all_pairs_shortest_path(G)
print(path[1])
{1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 4], 5: [1, 5], 6: [1, 4, 6]}
計算2:找圖中兩個點的最短路徑
import networkx as nx
G=nx.Graph()
G.add_nodes_from([1,2,3,4])
G.add_edge(1,2)
G.add_edge(3,4)
try:
n=nx.shortest_path_length(G,1,4)
print (n)
except nx.NetworkXNoPath:
print ('No path')
No path
強連通、弱連通
- 強連通:有向圖中任意兩點v1、v2間存在v1到v2的路徑(path)及v2到v1的路徑。
- 弱聯通:將有向圖的所有的有向邊替換為無向邊,所得到的圖稱為原圖的基圖。如果一個有向圖的基圖是連通圖,則有向圖是弱連通圖。
距離
例1:弱連通
#-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
#G = nx.path_graph(4, create_using=nx.Graph())
#0 1 2 3
G = nx.path_graph(4, create_using=nx.DiGraph()) #默認生成節點0 1 2 3,生成有向變0->1,1->2,2->3
G.add_path([7, 8, 3]) #生成有向邊:7->8->3
for c in nx.weakly_connected_components(G):
print (c)
print ([len(c) for c in sorted(nx.weakly_connected_components(G), key=len, reverse=True)])
nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()
{0, 1, 2, 3, 7, 8}
[6]

例2:強連通
#-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
#G = nx.path_graph(4, create_using=nx.Graph())
#0 1 2 3
G = nx.path_graph(4, create_using=nx.DiGraph())
G.add_path([3, 8, 1])
#for c in nx.strongly_connected_components(G):
# print c
#
#print [len(c) for c in sorted(nx.strongly_connected_components(G), key=len, reverse=True)]
con = nx.strongly_connected_components(G)
print (con)
print (type(con))
print (list(con))
nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()
<generator object strongly_connected_components at 0x0000018ECC82DD58>
<class 'generator'>
[{8, 1, 2, 3}, {0}]

6 子圖
#-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_path([5, 6, 7, 8])
sub_graph = G.subgraph([5, 6, 8])
#sub_graph = G.subgraph((5, 6, 8)) #ok 一樣
nx.draw(sub_graph)
plt.savefig("youxiangtu.png")
plt.show()

條件過濾
原圖
#-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
road_nodes = {'a':{'id':1}, 'b':{'id':1}, 'c':{'id':3}, 'd':{'id':4}}
road_edges = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'd')]
G.add_nodes_from(road_nodes)
G.add_edges_from(road_edges)
nx.draw(G)
plt.savefig("youxiangtu.png")
plt.show()

過濾函數
#-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
def flt_func_draw():
flt_func = lambda d: d['id'] != 1
return flt_func
road_nodes = {'a':{'id':1}, 'b':{'id':1}, 'c':{'id':3}, 'd':{'id':4}}
road_edges = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'd')]
G.add_nodes_from(road_nodes.items())
G.add_edges_from(road_edges)
flt_func = flt_func_draw()
part_G = G.subgraph(n for n, d in G.nodes_iter(data=True) if flt_func(d))
nx.draw(part_G)
plt.savefig("youxiangtu.png")
plt.show()

pred,succ
#-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
road_nodes = {'a':{'id':1}, 'b':{'id':1}, 'c':{'id':3}}
road_edges = [('a', 'b'), ('a', 'c'), ('c', 'd')]
G.add_nodes_from(road_nodes.items())
G.add_edges_from(road_edges)
print( G.nodes())
print (G.edges())
print ("a's pred ", G.pred['a'])
print ("b's pred ", G.pred['b'])
print ("c's pred ", G.pred['c'])
print ("d's pred ", G.pred['d'])
print ("a's succ ", G.succ['a'])
print ("b's succ ", G.succ['b'])
print ("c's succ ", G.succ['c'])
print ("d's succ ", G.succ['d'])
nx.draw(G)
plt.savefig("wuxiangtu.png")
plt.draw()
['a', 'b', 'c', 'd']
[('a', 'b'), ('a', 'c'), ('c', 'd')]
a's pred {}
b's pred {'a': {}}
c's pred {'a': {}}
d's pred {'c': {}}
a's succ {'b': {}, 'c': {}}
b's succ {}
c's succ {'d': {}}
d's succ {}
畫圖小技巧
%pylab inline
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默認字體
mpl.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負號 '-' 顯示為方塊的問題
import networkx as nx
g=nx.Graph()
g.add_edge('張三','李四')
g.add_edge('張三','王五')
nx.draw(g,with_labels=True)
plt.show()
Populating the interactive namespace from numpy and matplotlib

networkx 有四種圖 Graph 、DiGraph、MultiGraph、MultiDiGraph,分別為無多重邊無向圖、無多重邊有向圖、有多重邊無向圖、有多重邊有向圖。
import networkx as nx
G = nx.Graph() # 創建空的網絡圖
G = nx.DiGraph()
G = nx.MultiGraph()
G = nx.MultiDiGraph()
G.add_node('a')#添加點a
G.add_node(1,1)#用坐標來添加點
G.add_edge('x','y')#添加邊,起點為x,終點為y
G.add_weight_edges_from([('x','y',1.0)])#第三個輸入量為權值
#也可以
L = [[('a','b',5.0),('b','c',3.0),('a','c',1.0)]]
G.add_weight_edges_from([(L)])
nx.draw(G)
plt.show() # 圖像顯示
為了讓圖形更精美我們詳解 nx.draw()
nx.draw(G, pos=None, ax=None, **kwds)
pos指的是布局,主要有spring_layout,random_layout,circle_layout,shell_layout。node_color指節點顏色,有rbykw,同理edge_color.with_labels指節點是否顯示名字size表示大小font_color表示字的顏色。
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.25) for node in G.nodes()]
nx.draw(G, cmap = plt.get_cmap('jet'), node_color = values)
plt.show()

import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.25) for node in G.nodes()]
# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]
# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'),
node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab
G = nx.DiGraph()
G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2)
G.add_edges_from([('B','C'),('E','F')], weight=3)
G.add_edges_from([('C','F')], weight=4)
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_labels=dict([((u,v,),d['weight'])
for u,v,d in G.edges(data=True)])
red_edges = [('C','D'),('D','A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]
pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()

可哈希的:一個對象在它的生存期從來不會被改變(擁有一個哈希方法),能和其他對象區別(有比較方法) ↩︎
