edge_subgraph

MultiDiGraph.edge_subgraph(edges)[source]

Returns the subgraph induced by the specified edges.

The induced subgraph contains each edge in edges and each node incident to any one of those edges.

Parameters:edges (iterable) – An iterable of edges in this graph.
Returns:G – An edge-induced subgraph of this graph with the same edge attributes.
Return type:Graph

Notes

The graph, edge, and node attributes in the returned subgraph are references to the corresponding attributes in the original graph. Thus changes to the node or edge structure of the returned graph will not be reflected in the original graph, but changes to the attributes will.

To create a subgraph with its own copy of the edge or node attributes, use:

>>> nx.MultiDiGraph(G.edge_subgraph(edges))  

If edge attributes are containers, a deep copy of the attributes can be obtained using:

>>> G.edge_subgraph(edges).copy()  

Examples

Get a subgraph induced by only those edges that have a certain attribute:

>>> # Create a graph in which some edges are "good" and some "bad".
>>> G = nx.MultiDiGraph()
>>> key = G.add_edge(0, 1, key=0, good=True)
>>> key = G.add_edge(0, 1, key=1, good=False)
>>> key = G.add_edge(1, 2, key=0, good=False)
>>> key = G.add_edge(1, 2, key=1, good=True)
>>> # Keep only those edges that are marked as "good".
>>> edges = G.edges(keys=True, data='good')
>>> edges = ((u, v, k) for (u, v, k, good) in edges if good)
>>> H = G.edge_subgraph(edges)
>>> list(H.edges(keys=True, data=True))
[(0, 1, 0, {'good': True}), (1, 2, 1, {'good': True})]