1. 創(chuàng)建一個(gè)圖
import networkx as nx g = nx.Graph() g.clear() #將圖上元素清空
所有的構(gòu)建復(fù)雜網(wǎng)絡(luò)圖的操作基本都圍繞這個(gè)g來執(zhí)行。
2. 節(jié)點(diǎn)
節(jié)點(diǎn)的名字可以是任意數(shù)據(jù)類型的,添加一個(gè)節(jié)點(diǎn)是
g.add_node(1) g.add_node("a") g.add_node("spam")
添加一組節(jié)點(diǎn),就是提前構(gòu)建好了一個(gè)節(jié)點(diǎn)列表,將其一次性加進(jìn)來,這跟后邊加邊的操作是具有一致性的。
g.add_nodes_from([2,3]) or a = [2,3] g.add_nodes_from(a)
這里需要值得注意的一點(diǎn)是,對(duì)于add_node加一個(gè)點(diǎn)來說,字符串是只添加了名字為整個(gè)字符串的節(jié)點(diǎn)。但是對(duì)于
add_nodes_from加一組點(diǎn)來說,字符串表示了添加了每一個(gè)字符都代表的多個(gè)節(jié)點(diǎn),exp: g.add_node("spam") #添加了一個(gè)名為spam的節(jié)點(diǎn) g.add_nodes_from("spam") #添加了4個(gè)節(jié)點(diǎn),名為s,p,a,m g.nodes() #可以將以上5個(gè)節(jié)點(diǎn)打印出來看看
加一組從0開始的連續(xù)數(shù)字的節(jié)點(diǎn)
H = nx.path_graph(10) g.add_nodes_from(H) #將0~9加入了節(jié)點(diǎn) #但請(qǐng)勿使用g.add_node(H)
刪除節(jié)點(diǎn)
與添加節(jié)點(diǎn)同理
g.remove_node(node_name) g.remove_nodes_from(nodes_list)
3. 邊
邊是由對(duì)應(yīng)節(jié)點(diǎn)的名字的元組組成,加一條邊
g.add_edge(1,2) e = (2,3) g.add_edge(*e) #直接g.add_edge(e)數(shù)據(jù)類型不對(duì),*是將元組中的元素取出
加一組邊
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. 查看圖上點(diǎn)和邊的信息
g.number_of_nodes() #查看點(diǎn)的數(shù)量 g.number_of_edges() #查看邊的數(shù)量 g.nodes() #返回所有點(diǎn)的信息(list) g.edges() #返回所有邊的信息(list中每個(gè)元素是一個(gè)tuple) g.neighbors(1) #所有與1這個(gè)點(diǎn)相連的點(diǎn)的信息以列表的形式返回 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. 點(diǎn)的屬性設(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,會(huì)將節(jié)點(diǎn)名字和屬性信息一起輸出
7. 邊的屬性設(shè)置
通過上文中對(duì)g[1]的介紹可知邊的屬性在{}中顯示出來,我們可以根據(jù)這個(gè)秀改變的屬性
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),如果你有一個(gè)money屬性,那么也可以修改為weight='money',那么結(jié)果就是對(duì)money求和了 print DG.successors(1) # [2,4] 表示1的后繼節(jié)點(diǎn)有2和4 print DG.predecessors(1) # [3] 表示只有一個(gè)節(jié)點(diǎn)3有指向1的連邊
Multigraphs
簡(jiǎn)答從字面上理解就是這種復(fù)雜網(wǎng)絡(luò)圖允許你相同節(jié)點(diǎn)之間允許出現(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表示每一個(gè)起始點(diǎn),nbrs是一個(gè)字典,字典中的每一個(gè)元素包含了這個(gè)起始點(diǎn)連接的點(diǎn)和這兩個(gè)點(diǎn)連邊對(duì)應(yīng)的屬性 print n, nbrs for nbr,eattr in nbrs.items(): # nbr表示跟n連接的點(diǎn),eattr表示這兩個(gè)點(diǎn)連邊的屬性集合,這里只設(shè)置了weight,如果你還設(shè)置了color,那么就可以通過eattr['color']訪問到對(duì)應(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()接口計(jì)算最短路程
>>> 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)造方法,選擇其中一個(gè)
nx.draw(g) nx.draw_random(g) #點(diǎn)隨機(jī)分布 nx.draw_circular(g) #點(diǎn)的分布形成一個(gè)環(huán) nx.draw_spectral(g)
最后將圖形表現(xiàn)出來
import matplotlib.pyplot as plt plt.show()
將圖片保存到下來
nx.draw(g) plt.savefig("path.png")
修改節(jié)點(diǎn)顏色,邊的顏色
g = nx.cubical_graph() nx.draw(g, pos=nx.spectral_layout(g), nodecolor='r', edge_color='b') plt.show()
13. 圖形種類的選擇
Graph Type | NetworkX Class |
---|---|
簡(jiǎn)單無向圖 | Graph() |
簡(jiǎn)單有向圖 | DiGraph() |
有自環(huán) | Grap(),DiGraph() |
有重邊 | MultiGraph(), MultiDiGraph() |
reference:https://networkx.github.io/documentation/networkx-1.10/reference/classes.html
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
