2

I am using python, NetworkX and Matplotlib, I want to connect same node from two graphs For example two graphs:G1 and G2

G1=nx.Graph()
G2=nx.Graph()
G1.add_nodes_from([0,1,2,3,9,8,10,11,12,13,14])
G2.add_nodes_from([4,5,6,7,8])
G1.add_edges_from([(0,1),(2,3),(2,9),(2,12),(1,9),(10,8),(8,11),(8,13),(8,14)])
G2.add_edges_from([(4,5),(6,7),(4,8)])
pos1=nx.spring_layout(G1,k=0.2,iterations=30)
pos2=nx.spring_layout(G2)
for k,v in pos2.items():
    v[0] = v[0] +3
nx.draw(G1,pos1,with_labels=True,node_color='b')
nx.draw(G2,pos2,with_labels=True)

The image is like this:

My question is how can I connect the same nodes from two graphs? (node "8" is in both of them)

I want node"8"(blue) link with node"8"(red).      

I also used G3= nx.compos(G1,G2), but I don't know how to draw the nodes(color =blue,from G1) at the right side and the other nodes at the left side(color =red, from G2). So I gave up this method.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
YouXing
  • 33
  • 4

2 Answers2

0

If you just want to draw a line connecting the two nodes, then just draw one with matplotlib and make sure that the zorder is low:

import matplotlib.pyplot as plt
x1, y1 = pos1[8]
x2, y2 = pos2[8]
plt.plot([x1, x2], [y1, y2], zorder=0)
Paul Brodersen
  • 11,221
  • 21
  • 38
  • Thanks for your help, and the method was worked. But I found should use compose to make the graph beautiful, I will edit my question. Anyway thanks for your help – YouXing Nov 30 '17 at 03:41
0

OK, finally I decided use the method of nx.compose and It' worked After the line pos2 in the command, add those:

D_1=G2.nodes()
G3=nx.compose(G1,G2)
pos3= nx.spring_layout(G3)
for k, v in pos3.items():
    if k in D_1:
        v[0] = v[0] +10 
nx.draw_networkx_nodes(G3,pos3,nodelist=G1.nodes(),node_color='b')
nx.draw_networkx_nodes(G3,pos3,nodelist=G2.nodes())
nx.draw_networkx_edges(G3,pos3,edgelist=G1.edges())
nx.draw_networkx_edges(G3,pos3,edgelist=G2.edges())
nx.draw_networkx_labels(G3,pos3)

The image will became this enter image description here

YouXing
  • 33
  • 4