Search code examples
pythongraphnodesnetworkx

Constructing a network with multiple graphs


I want to create a network that is composed of copies of graphs, for example the Karate Club network. So, I want my overall network to have, for example, 2 copies of the Karate Club network, where the two karate networks are connected by an adding an edge.

Is there a way I can do this in networkx? I have so far created the copies of the the Karate Club networks, but I am struggling to put them into one network so they are mirrored.

Thanks in advance.


Solution

  • You are looking for the compose method, see more explanation on this question: Combine (join) networkx Graphs

    If you want to join the same graph, you need to make sure that the node sets are disjoint, which can be achieved via convert_node_labels_to_integers. A full example with two karate club networks and an edge between the graphs:

    import networkx as nx
    import matplotlib.pylab as plt
    
    karate_1 = nx.karate_club_graph()
    karate_2 = nx.karate_club_graph()
    
    # relabel nodes to create disjoint nodes
    karate_1 = nx.convert_node_labels_to_integers(karate_1, first_label=0)
    print(len(karate_1))
    karate_2 = nx.convert_node_labels_to_integers(karate_2, first_label=len(karate_1))
    
    joint_graph = nx.compose(karate_1, karate_2)
    print(len(joint_graph))
    
    joint_graph.add_edge(0, 34)
    
    nx.draw(joint_graph)
    plt.show()