Search code examples
pythongraphnodesnetworkxedges

Adding multiple directed edges in networkx


I know this should be very basic but I have no clue how to do this using networkx. What I am trying to do is to create a MultiDiGraph with 20 nodes. There would be 2 edges connecting each nodes to each other, one away from the node and the other going towards the node. I am unable to create those edges. Any help would be greatly appreciated. It should look something like the picture I have attached.


Solution

  • You could create a graph, and then convert it to a directed graph. In this way you get edges in both directions:

    import networkx as nx
    
    g = nx.Graph()
    g.add_edges_from([(0, 1), (1, 2), (1, 3)])
    g = g.to_directed()
    
    >>> g.edges
    OutEdgeView([(0, 1), (1, 0), (1, 2), (1, 3), (2, 1), (3, 1)])
    

    If you want to generate a complete directed graph with n nodes:

    import networkx as nx
    
    g = nx.complete_graph(4).to_directed()
    
    >>> g.edges
    OutEdgeView([(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)])