2014-02-12 24 views
5

的圖形對象中尋找不同的圖我有一個巨大的數據集圖形 - 讓我們說這是這樣的,但在一個更大級別:在networkx

1 -> 2 
3 -> 4 

1,2,3,4的節點和箭頭是有向邊緣。比方說,他們都在一個單一的圖形對象:

import networkx as nx 
G = nx.DiGraph() 
G.add_nodes_from([1,2,3,4]) 
G.add_edge(1,2) 
G.add_edge(3,4) 

給定一個對象這樣的,其中有一個圖中的兩個小圖,我們怎麼能拉出每個迷你圖? 我覺得這個必須有一些詞彙嗎? 我最終的結果會是什麼樣子:

for mini_graph in G: 
    print mini_graph.nodes() 

... 
[1,2] 
[3,4] 
+1

我認爲你可以使用['weakly_connected_component_subgraphs'(http://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.components.weakly_connected.weakly_connected_component_subgraphs.html#networkx.algorithms.components。 weakly_connected.weakly_connected_component_subgraphs),如果是這樣,這是這個重複:http://stackoverflow.com/questions/18643789/how-to-find-subgraphs-in-a-directed-graph-without-converting-to-undirected-圖 – EdChum

+0

也相關:http://stackoverflow.com/questions/13914920/networkx-extract-the-smallest-connected-subgraph。這取決於你如何在這裏定義子圖 – EdChum

回答

8

如果圖的部分是真正的不相交(按你的小例子),然後考慮connected_component_subgraphs()提取子圖。

這隻適用於無向圖,所以如果您使用的是有向圖,那麼您需要首先轉換爲無向圖。

import networkx as nx 
G = nx.DiGraph() 
G.add_nodes_from([1,2,3,4]) 
G.add_edge(1,2) 
G.add_edge(3,4) 

# make an undirected copy of the digraph 
UG = G.to_undirected() 

# extract subgraphs 
sub_graphs = nx.connected_component_subgraphs(UG) 

for i, sg in enumerate(sub_graphs): 
    print "subgraph {} has {} nodes".format(i, sg.number_of_nodes()) 
    print "\tNodes:", sg.nodes(data=True) 
    print "\tEdges:", sg.edges() 

這將產生:

subgraph 1 has 2 nodes 
    Nodes: [(1, {}), (2, {})] 
    Edges: [(1, 2)] 
subgraph 1 has 2 nodes 
    Nodes: [(3, {}), (4, {})] 
    Edges: [(3, 4)] 

,你可以使用子節點標籤在初始圖上的數據進行操作,

sg.nodes()[0] in G 
>>> True 

讀通過EdChum聯答案,似乎weakly_connected_component_subgraphs()在有向圖上運行,但將其視爲無向圖,因此保存副本可能至關重要。但是,目前有關此功能的文檔和相關功能weakly_connected_components()有點薄。