Skip to content
Advertisement

Combine (join) networkx Graphs

Say I have two networkx graphs, G and H:

JavaScript

What is the best way to join the two networkx graphs?

I’d like to preserve the node names (note the common nodes, 2 to 7). When I used nx.disjoint_union(G,H), this did not happen:

JavaScript

The H node labels were changed (not what I want). I want to join the graphs at the nodes with the same number.

Note. This is not a duplicate of Combine two weighted graphs in NetworkX

Advertisement

Answer

The function you’re looking for is compose, which produces a graph with all the edges and all the nodes that are in both graphs. If both graphs have a node with the same name, then a single copy ends up in the new graph. Similarly if the same edge exists in both. Here’s an example, including edge/node attributes:

JavaScript

These preserve attributes, but obviously if there is a conflict this is not possible. The attributes of H take precedence.

There are also other options to do the symmetric difference, intersection, …

If you have multiple graphs to join together, you can use compose_all, which just wraps a for loop around compose.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement