[SOLVED] Merge and interact between two graphs in networkx

Issue

This Content is from Stack Overflow. Question asked by I’mStuckOnLine911

There is way for merge two graphs G and H side by side or even interact between them after computing layout? I need same spring look for single and merged graph.

G = nx.Graph() pos = nx.spring_layout(G) 
nx.draw_networkx(G, pos, edge_color=colors, **options, node_color=colors_nodes, width=widths)
H = nx.Graph()
pos2 = nx.spring_layout(H)
nx.draw_networkx(H, pos2, edge_color=colors, **options, node_color=colors_nodes, width=widths)

The final look should be like this Graph



Solution

I believe you would be looking for the disjoint_union function or the union depending upon your use case and the nature of your graphs’ nodes being distinct integers or not

Example would be:

 G = nx.Graph([(0, 1), (0, 2), (1, 2)])
 H = nx.Graph([(0, 1), (0, 3), (1, 3), (1, 2)])
 I = nx.union(G, H, rename=("G", "H"))
 J = nx.Graph(I)
 nx.draw_networkx(J, pos, edge_color=colors, **options, node_color=colors_nodes, width=widths)
 


This Question was asked in StackOverflow by I'mStuckOnLine911 and Answered by Zero It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?