目錄
- 創(chuàng)建一個圖
- 節(jié)點
- 邊
- 查看圖上點和邊的信息
- 圖的屬性設(shè)置
- 點的屬性設(shè)置
- 邊的屬性設(shè)置
- 不同類型的圖(有向圖Directed graphs , 重邊圖 Multigraphs)
- 圖的遍歷
- 圖生成和圖上的一些操作
- 圖上分析
- 圖的繪制
1. 創(chuàng)建一個圖
import networkx as nx
g = nx.Graph()
g.clear() #將圖上元素清空
所有的構(gòu)建復(fù)雜網(wǎng)絡(luò)圖的操作基本都圍繞這個g來執(zhí)行姚垃。
2. 節(jié)點
節(jié)點的名字可以是任意數(shù)據(jù)類型的,添加一個節(jié)點是
g.add_node(1)
g.add_node("a")
g.add_node("spam")
添加一組節(jié)點,就是提前構(gòu)建好了一個節(jié)點列表,將其一次性加進(jìn)來,這跟后邊加邊的操作是具有一致性的们镜。
g.add_nodes_from([2,3])
or
a = [2,3]
g.add_nodes_from(a)
這里需要值得注意的一點是缴渊,對于add_node加一個點來說仑乌,字符串是只添加了名字為整個字符串的節(jié)點兑燥。但是對于add_nodes_from加一組點來說亮瓷,字符串表示了添加了每一個字符都代表的多個節(jié)點,exp:
g.add_node("spam") #添加了一個名為spam的節(jié)點
g.add_nodes_from("spam") #添加了4個節(jié)點降瞳,名為s,p,a,m
g.nodes() #可以將以上5個節(jié)點打印出來看看
加一組從0開始的連續(xù)數(shù)字的節(jié)點
H = nx.path_graph(10)
g.add_nodes_from(H) #將0~9加入了節(jié)點
#但請勿使用g.add_node(H)
刪除節(jié)點
與添加節(jié)點同理
g.remove_node(node_name)
g.remove_nodes_from(nodes_list)
3. 邊
邊是由對應(yīng)節(jié)點的名字的元組組成嘱支,加一條邊
g.add_edge(1,2)
e = (2,3)
g.add_edge(*e) #直接g.add_edge(e)數(shù)據(jù)類型不對,*是將元組中的元素取出
加一組邊
g.add_edges_from([(1,2),(1,3)])
g.add_edges_from([("a","spam") , ("a",2)])
通過nx.path_graph(n)加一系列連續(xù)的邊
n = 10
H = nx.path_graph(n)
g.add_edges_from(H.edges()) #添加了0~1,1~2 ... n-2~n-1這樣的n-1條連續(xù)的邊
刪除邊
同理添加邊的操作
g.remove_edge(edge)
g.remove_edges_from(edges_list)
4. 查看圖上點和邊的信息
g.number_of_nodes() #查看點的數(shù)量
g.number_of_edges() #查看邊的數(shù)量
g.nodes() #返回所有點的信息(list)
g.edges() #返回所有邊的信息(list中每個元素是一個tuple)
g.neighbors(1) #所有與1這個點相連的點的信息以列表的形式返回
g[1] #查看所有與1相連的邊的屬性挣饥,格式輸出:{0: {}, 2: {}} 表示1和0相連的邊沒有設(shè)置任何屬性(也就是{}沒有信息)除师,同理1和2相連的邊也沒有任何屬性
method | explanation |
---|---|
Graph.has_node (n) |
Return True if the graph contains the node n. |
Graph.__contains__ (n) |
Return True if n is a node, False otherwise. |
Graph.has_edge (u, v) |
Return True if the edge (u,v) is in the graph. |
Graph.order () |
Return the number of nodes in the graph. |
Graph.number_of_nodes () |
Return the number of nodes in the graph. |
Graph.__len__ () |
Return the number of nodes. |
Graph.degree ([nbunch, weight]) |
Return the degree of a node or nodes. |
Graph.degree_iter ([nbunch, weight]) |
Return an iterator for (node, degree). |
Graph.size ([weight]) |
Return the number of edges. |
Graph.number_of_edges ([u, v]) |
Return the number of edges between two nodes. |
Graph.nodes_with_selfloops () |
Return a list of nodes with self loops. |
Graph.selfloop_edges ([data, default]) |
Return a list of selfloop edges. |
Graph.number_of_selfloops () |
Return the number of selfloop edges. |
5. 圖的屬性設(shè)置
為圖賦予初始屬性
g = nx.Graph(day="Monday")
g.graph # {'day': 'Monday'}
修改圖的屬性
g.graph['day'] = 'Tuesday'
g.graph # {'day': 'Tuesday'}
6. 點的屬性設(shè)置
g.add_node('benz', money=10000, fuel="1.5L")
print g.node['benz'] # {'fuel': '1.5L', 'money': 10000}
print g.node['benz']['money'] # 10000
print g.nodes(data=True) # data默認(rèn)false就是不輸出屬性信息,修改為true扔枫,會將節(jié)點名字和屬性信息一起輸出
7. 邊的屬性設(shè)置
通過上文中對g[1]的介紹可知邊的屬性在{}中顯示出來汛聚,我們可以根據(jù)這個秀改變的屬性
g.clear()
n = 10
H = nx.path_graph(n)
g.add_nodes_from(H)
g.add_edges_from(H.edges())
g[1][2]['color'] = 'blue'
g.add_edge(1, 2, weight=4.7)
g.add_edges_from([(3,4),(4,5)], color='red')
g.add_edges_from([(1,2,{'color':'blue'}), (2,3,{'weight':8})])
g[1][2]['weight'] = 4.7
g.edge[1][2]['weight'] = 4
8. 不同類型的圖(有向圖Directed graphs , 重邊圖 Multigraphs)
-
Directed graphs
DG = nx.DiGraph() DG.add_weighted_edges_from([(1,2,0.5), (3,1,0.75), (1,4,0.3)]) # 添加帶權(quán)值的邊 print DG.out_degree(1) # 打印結(jié)果:2 表示:找到1的出度 print DG.out_degree(1, weight='weight') # 打印結(jié)果:0.8 表示:從1出去的邊的權(quán)值和,這里權(quán)值是以weight屬性值作為標(biāo)準(zhǔn)短荐,如果你有一個money屬性贞岭,那么也可以修改為weight='money',那么結(jié)果就是對money求和了 print DG.successors(1) # [2,4] 表示1的后繼節(jié)點有2和4 print DG.predecessors(1) # [3] 表示只有一個節(jié)點3有指向1的連邊
?
-
Multigraphs
簡答從字面上理解就是這種復(fù)雜網(wǎng)絡(luò)圖允許你相同節(jié)點之間允許出現(xiàn)重邊
MG=nx.MultiGraph() MG.add_weighted_edges_from([(1,2,.5), (1,2,.75), (2,3,.5)]) print MG.degree(weight='weight') # {1: 1.25, 2: 1.75, 3: 0.5} GG=nx.Graph() for n,nbrs in MG.adjacency_iter(): for nbr,edict in nbrs.items(): minvalue=min([d['weight'] for d in edict.values()]) GG.add_edge(n,nbr, weight = minvalue) print nx.shortest_path(GG,1,3) # [1, 2, 3]
9. 圖的遍歷
g = nx.Graph()
g.add_weighted_edges_from([(1,2,0.125),(1,3,0.75),(2,4,1.2),(3,4,0.375)])
for n,nbrs in g.adjacency_iter(): #n表示每一個起始點搓侄,nbrs是一個字典瞄桨,字典中的每一個元素包含了這個起始點連接的點和這兩個點連邊對應(yīng)的屬性
print n, nbrs
for nbr,eattr in nbrs.items():
# nbr表示跟n連接的點,eattr表示這兩個點連邊的屬性集合讶踪,這里只設(shè)置了weight芯侥,如果你還設(shè)置了color,那么就可以通過eattr['color']訪問到對應(yīng)的color元素
data=eattr['weight']
if data<0.5: print('(%d, %d, %.3f)' % (n,nbr,data))
10. 圖生成和圖上的一些操作
下方的這些操作都是在networkx包內(nèi)的方法
subgraph(G, nbunch) - induce subgraph of G on nodes in nbunch
union(G1,G2) - graph union
disjoint_union(G1,G2) - graph union assuming all nodes are different
cartesian_product(G1,G2) - return Cartesian product graph
compose(G1,G2) - combine graphs identifying nodes common to both
complement(G) - graph complement
create_empty_copy(G) - return an empty copy of the same graph class
convert_to_undirected(G) - return an undirected representation of G
convert_to_directed(G) - return a directed representation of G
11. 圖上分析
g = nx.Graph()
g.add_edges_from([(1,2), (1,3)])
g.add_node("spam")
nx.connected_components(g) # [[1, 2, 3], ['spam']] 表示返回g上的不同連通塊
sorted(nx.degree(g).values())
通過構(gòu)建權(quán)值圖乳讥,可以直接快速利用dijkstra_path()接口計算最短路程
>>> G=nx.Graph()
>>> e=[('a','b',0.3),('b','c',0.9),('a','c',0.5),('c','d',1.2)]
>>> G.add_weighted_edges_from(e)
>>> print(nx.dijkstra_path(G,'a','d'))
['a', 'c', 'd']
12. 圖的繪制
下面是4種圖的構(gòu)造方法柱查,選擇其中一個
nx.draw(g)
nx.draw_random(g) #點隨機分布
nx.draw_circular(g) #點的分布形成一個環(huán)
nx.draw_spectral(g)
最后將圖形表現(xiàn)出來
import matplotlib.pyplot as plt
plt.show()
將圖片保存到下來
nx.draw(g)
plt.savefig("path.png")
修改節(jié)點顏色,邊的顏色
g = nx.cubical_graph()
nx.draw(g, pos=nx.spectral_layout(g), nodecolor='r', edge_color='b')
plt.show()
13. 圖形種類的選擇
Graph Type | NetworkX Class |
---|---|
簡單無向圖 | Graph() |
簡單有向圖 | DiGraph() |
有自環(huán) | Grap(),DiGraph() |
有重邊 | MultiGraph(), MultiDiGraph() |
reference:https://networkx.github.io/documentation/networkx-1.10/reference/classes.html