Search code examples
pythongraph

Operations with two graphs


I am having issues with understanding and visualization of graph operations (union, intersection, difference and addition).

I tried to use union1d as one of operations and reshape as a 1d-array product from union1d function into 2d-array. The code works, but not as wanted.

I don't really understand what could be my problem at solving it. I would be really appreciated if somebody could explain my problem and, maybe, fix my code.

Here's what I got as a result: output

Here's my code:

import networkx as nx
import numpy as np

import matplotlib.pyplot as plt

G = nx.Graph()

plt.figure(figsize =(1, 5))
G.add_edges_from([(1, 2), (2, 3), (2, 3), (2, 4), (2, 5), (3, 4),
                        (4, 5), (4, 6), (5, 7), (5, 8)])

# First Graph created
plt.subplot(311)
nx.draw_networkx(G)

H = nx.Graph()
H.add_edges_from([(5, 7), (7,5), (7, 4),
                (1, 2), (7, 8), (9, 10)])

# Second Graph created
plt.subplot(312)
nx.draw_networkx(H)
ee = np.union1d(G,H)

ee = np.reshape(G, (-1, 2))


# Third Graph Created

I = nx.Graph()
I.add_edges_from(ee)
plt.subplot(313)
nx.draw_networkx(I)

plt.show()

Solution

  • You should use networkx operator for the union or intersection of 2 Graphs.

    import networkx as nx
    import numpy as np
    
    import matplotlib.pyplot as plt
    
    G = nx.Graph()
    
    plt.figure(figsize =(1, 5))
    G.add_edges_from([(1, 2), (2, 3), (2, 3), (2, 4), (2, 5), (3, 4),
                            (4, 5), (4, 6), (5, 7), (5, 8)])
    
    print(G)
    # First Graph created
    plt.subplot(411)
    nx.draw_networkx(G)
    
    H = nx.Graph()
    H.add_edges_from([(5, 7), (7,5), (7, 4),
                    (1, 2), (7, 8), (9, 10)])
    
    # Second Graph created
    plt.subplot(412)
    nx.draw_networkx(H)
    
    # Third Graph Created
    I=nx.compose(G,H)
    plt.subplot(413)
    nx.draw_networkx(I)
    
    # Fourth Graph Created
    J=nx.intersection(G,H)
    plt.subplot(414)
    nx.draw_networkx(J)
    
    
    plt.show()
    

    see below union (compose) and intersection: enter image description here