2
$\begingroup$

In an undirected graph, I would like to order its nodes according to their degree. However, to do this I have to enter the edges of the graph first. When I do this, NetworkX in Python reads the nodes from the entries of the edges and doesn't consider the contribution of the add_nodes_from command. Is there any way to overcome this problem? Here is a sample of code I'm using:

g = nx.Graph()
weighted_edges =    [(4,3,150),(1,2,15),(1,4,100),(1,3,100),(1,5,130)
                    ,(2,3,205),(2,4,211),(2,5,200),(3,5,100),(4,5,10)]
#Sorting edges according to node degree 
sorted_edges = sorted(g.degree(weight='weight'), key=lambda x: x[1], reverse=True)
# extract the sorted nodes 
nodes = []
for e in range(len(sorted_edges)):
   temp = sorted_edges[e][0]
   nodes.append(temp)

g.add_nodes_from(nodes)
g.add_weighted_edges_from(weighted_edges)

according to the above sample of code, print(nodes) output is an empty set, since add_weighted_edges_from is coming after. When we add the edges first, g.nodes outputs following the order edge entries. nodes are meant to be the sorted nodes according to their degree, and g.nodes are the nodes according to the graph edges entries. I appreciate your help!

$\endgroup$

2 Answers 2

2
$\begingroup$

I know this is not a typical answer, but I decided to post this tweak to help others when they are facing the same problem. I have added another initiation for the graph method using the same name of the graph g=nx.graph() just before the definition of the sorted nodes, such that the graph will consider the sorted nodes as g.nodes, the code will be such that

g = nx.Graph()
weighted_edges =    [(4,3,150),(1,2,15),(1,4,100),(1,3,100),(1,5,130)
                     ,(2,3,205),(2,4,211),(2,5,200),(3,5,100),(4,5,10)]
#Sorting edges according to node degree 
sorted_edges = sorted(g.degree(weight='weight'), key=lambda x: x[1], reverse=True)
# extract the sorted nodes 
nodes = []
for e in range(len(sorted_edges)):
    temp = sorted_edges[e][0]
    nodes.append(temp)
g=nx.graph() # this line was added to restart the graph definition
g.add_nodes_from(nodes)
g.add_weighted_edges_from(weighted_edges)
print (g.nodes)
output: NodeView((2, 3, 4, 5, 1)) # g.nodes are sorted according to the node degree
$\endgroup$
0
$\begingroup$

You can create your graph just like this

g = nx.DiGraph()
g.add_weighted_edges_from([(4,3,150),(1,2,15),(1,4,100),(1,3,100),(1,5,130),
                           (2,3,205),(2,4,211),(2,5,200),(3,5,100),(4,5,10)])

Then to sort the nodes based on degree:

sorted_nodes = sorted(g.nodes, key=lambda x: g.degree(x), reverse=False)
g._node = {n: g.nodes[n] for n in sorted_nodes}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.