edge_subgraph#
- edge_subgraph(G, edges)[source]#
Returns a view of the subgraph induced by the specified edges.
The induced subgraph contains each edge in
edgesand each node incident to any of those edges.- Parameters:
- GNetworkX Graph
- edgesiterable
An iterable of edges. Edges not present in
Gare ignored.
- Returns:
- subgraphSubGraph View
A read-only edge-induced subgraph of
G. Changes toGare reflected in the view.
Notes
To create a mutable subgraph with its own copies of nodes edges and attributes use
subgraph.copy()orGraph(subgraph)If you create a subgraph of a subgraph recursively you can end up with a chain of subgraphs that becomes very slow with about 15 nested subgraph views. Luckily the edge_subgraph filter nests nicely so you can use the original graph as G in this function to avoid chains. We do not rule out chains programmatically so that odd cases like an
edge_subgraphof arestricted_viewcan be created.Examples
>>> G = nx.path_graph(5) >>> H = G.edge_subgraph([(0, 1), (3, 4)]) >>> list(H.nodes) [0, 1, 3, 4] >>> list(H.edges) [(0, 1), (3, 4)]
For multi graphs,
edgesmust include the edge keys:>>> G = nx.MultiGraph(G) >>> H = nx.edge_subgraph(G, [(0, 1, 0), (3, 4, 0)]) >>> list(H.edges) [(0, 1, 0), (3, 4, 0)]
Edge attributes can be used to filter multiedges:
>>> G.add_edge(0, 1, color="blue") 1 >>> G.add_edge(0, 1, color="green", weight=10) 2 >>> H = nx.edge_subgraph( ... G, ... ( ... (u, v, k) ... for u, v, k, clr in G.edges(keys=True, data="color") ... if clr == "green" ... ), ... ) >>> H.edges(keys=True, data=True) MultiEdgeDataView([(0, 1, 2, {'color': 'green', 'weight': 10})])