Chloe Tsui
Chloe Tsui

Reputation: 57

Networkx degree method didn't produce want I think it is

I ran the following script:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edge(1, 1, weight=2)
G.add_edge(1, 3, weight=2)
G.add_edge(1, 4, weight=1)
G.add_edge(1, 5, weight=5)
G.add_edge(2, 3, weight=3)
G.add_edge(2, 4, weight=2)
G.add_edge(3, 5, weight=4)

d = G.degree(1)

print G.edge[1]
print "Degree of node 1:", \
    G.degree(1)
print "Weighted degree of node 1:", \
    G.degree(1, weight='weight')

nx.draw(G)
plt.show()

The output is:

{1: {'weight': 2}, 3: {'weight': 2}, 4: {'weight': 1}, 5: {'weight': 5}}
Weighted degree: 5
Weighted degree: 12

And the drawing is like this:

degree of the graph

What confused me is:

Since there are 4 nodes adjacent to the node 1 (including itself), why the degree is 5?

Since the total weight of the adjacent edges of node 1 is 10 (2+2+1+5), why the degree method produced 12?

Thanks

Upvotes: 4

Views: 1065

Answers (2)

Zhengyang Liu
Zhengyang Liu

Reputation: 817

For an undirected graph, the degree of a vertex is equal to the number of adjacent vertices.

A special case is a loop, which adds two to the degree. This can be understood by letting each connection of the loop edge count as its own adjacent vertex. In other words, a vertex with a loop "sees" itself as an adjacent vertex from both ends of the edge thus adding two, not one, to the degree.

Upvotes: 6

unutbu
unutbu

Reputation: 879331

According to the definition of degree,

In graph theory, the degree (or valency) of a vertex of a graph is the number of edges incident to the vertex, with loops counted twice. (my emphasis)

So G.degree(1) is 5 since the loop from 1 to 1 is counted twice. The weighted degree also counts the loop twice, hence the total is 12 not 10, since the 1 node has weight 2.

Upvotes: 3

Related Questions