I am looking to "simplify" a NetworkX Directed Graph on a chosen set nodes. For e.g. I have this starting directed graph
And I want to see relationships in subgraph of only nodes [1,2,4 and 6]. i.e. as follows:
Basically I want to show the "resulting dependencies" on just my chosen nodes.
So far, I have tried the subgraph approach as follows.
Creating the original graph:
G = nx.DiGraph()
G.add_edges_from([(1,3),(3,4),(1,5),(5,6),(2,6),(4,6)])
..and then creating a subgraph:
chosen_nodes = [1,2,4,6]
SG = G.subgraph(chosen_nodes)
But the resulting subgraph doesn't retain any dependency relationship in edges other than the 2-6 and 4-6 relationship.
print(list(SG.edges))
>> [(4, 6), (2, 6)]
I think one clean way to get at this is to generate a subgraph of the transitive closure.
from networkx.algorithms.dag import transitive_closure
def dependency_graph(G, nodes):
return transitive_closure(G).subgraph(nodes)
print(dependency_graph(G, [1, 2, 4, 6]).edges)
>> [(1, 4), (1, 6), (4, 6), (2, 6)]