Search code examples
pythonnetworkx

Python networkx, how do I add x amount of edges per node?


I have a basic network graph in python using networkx, what I want to do is add a specific amount of edges per node, not directly determine the edges myself.

import networkx as nx
import matplotlib.pyplot as plt

hosts = 100
nodes = list(range(1,(hosts+1)))

H=nx.Graph()
H.add_nodes_from(nodes)
nx.draw_random(H)

enter image description here

So with this graph what I would like to do is specify "two edges per node" and then let python calculate the result. Is this possible?

Many thanks.


Solution

  • Your question sounds like a concept of configuration model in graph where it will return a random graph with the given degree sequence.

    See the networkx.generators.degree_seq.configuration_model documentation

    For example of a graph with degree [0, 1, 2, 3, 4]:

    import networkx as nx
    import matplotlib.pyplot as plt
    
    H = nx.configuration_model([i for i in range(5)])
    
    nx.draw_random(H)
    

    Note that sum of degrees must be an even number. Configuration model with degree from 0 to 4