Search code examples
python-3.xnetworkxgraph-theory

How to separate images of graphs?


I need to draw these complete graphs that the edges of the separate graphs don't intersect intercept each other. I have tried to use coordinates in matplotlib but it didn't work. That is the code:

import networkx as nx
import matplotlib.pyplot as plt


G=nx.Graph()
G.add_edge("1", "2")
G.add_edge("2","3")
G.add_edge("3","4")
G.add_edge("1","3")
G.add_edge("1","4")
G.add_edge("2","4")

pos = {1: (0, 0), 2: (1, 1), 3: (0, 1) , 4: (1, 0)}
        
F=nx.Graph()
F.add_edge("5", "6")
F.add_edge("6","7")
F.add_edge("7","8")
F.add_edge("5","7")
F.add_edge("5","8")
F.add_edge("6","8")

pos = {5: (10, 10), 6: (11, 11), 7: (10, 11) , 8: (11, 10)}

E=nx.Graph()
E.add_edge("9", "10")
E.add_edge("10","11")
E.add_edge("9","11")

pos = nx.random_layout(E)

Y=nx.Graph()
Y.add_node("12")

pos = nx.random_layout(Y)

nx.draw(G, with_labels = True, node_color = 'white')
nx.draw(F, with_labels = True, node_color = 'white')
nx.draw(E, with_labels = True, node_color = 'white')
nx.draw(Y, with_labels = True, node_color = 'white')

plt.savefig('labels.png')
plt.show()

Result

enter image description here


Solution

  • You create the pos variable and overwrite it multiple times without using it at any point. Simply create multiple with non overlapping drawing areas:

    import networkx as nx
    import matplotlib.pyplot as plt
    
    G = nx.Graph()
    G.add_edge("1", "2")
    G.add_edge("2", "3")
    G.add_edge("3", "4")
    G.add_edge("1", "3")
    G.add_edge("1", "4")
    G.add_edge("2", "4")
    
    pos_G = {"1": (0, 0), "2": (1, 1), "3": (0, 1), "4": (1, 0)}
    
    F = nx.Graph()
    F.add_edge("5", "6")
    F.add_edge("6", "7")
    F.add_edge("7", "8")
    F.add_edge("5", "7")
    F.add_edge("5", "8")
    F.add_edge("6", "8")
    
    pos_F = {"5": (10, 10), "6": (11, 11), "7": (10, 11), "8": (11, 10)}
    
    E = nx.Graph()
    E.add_edge("9", "10")
    E.add_edge("10", "11")
    E.add_edge("9", "11")
    
    pos_E = nx.random_layout(E)
    pos_E = {node: pos + 3 for node, pos in pos_E.items()}
    
    Y = nx.Graph()
    Y.add_node("12")
    
    pos_Y = nx.random_layout(Y)
    pos_Y = {node: pos + 5 for node, pos in pos_Y.items()}
    
    nx.draw(G, pos_G, with_labels=True, node_color='white')
    nx.draw(F, pos_F, with_labels=True, node_color='white')
    nx.draw(E, pos_E, with_labels=True, node_color='white')
    nx.draw(Y, pos_Y, with_labels=True, node_color='white')
    
    # plt.savefig('labels.png')
    plt.show()
    

    Result

    enter image description here