jjrr
jjrr

Reputation: 1148

Centralities in networkx weighted graph

I am not able to compute centralities for a simple NetworkX weighted graph.
Is it normal or I am rather doing something wrong?

I add edges with a simple add_edge(c[0],c[1],weight = my_values), where c[0],c[1] are strings (names of the nodes) and my_values integers, within a for loop. This is an example of the resulting edges:

('first node label', 'second node label', {'weight': 14})

(the number of nodes does't really matter — for now I keep it to only 20)

The edge list of my graph is a list of tuples, with (string_node1,string_node2,weight_dictionary) - everything looks fine, as I am also able to draw/save/read/ the graph...

Why?:

example:

{'first node name': 1.0,
...
'last node name': 1.0}

Thanks for your help.

Upvotes: 3

Views: 9628

Answers (3)

gusjc
gusjc

Reputation: 21

I know this is a pretty old question, but just wanted to point out that the reason why your degree centrality values are all 1 is probably because your graph is complete (i.e., all nodes are connected to every other node), and degree centrality refers to the proportion of nodes in the graph to which a node is connected.

Per networkx's documentation:

The degree centrality for a node v is the fraction of nodes it is connected to.

The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1 where n is the number of nodes in G.

Upvotes: 2

fjsj
fjsj

Reputation: 11240

For making closeness_centrality consider weight, you have to add a distance attribute of 1 / weight to graph edges, as suggested in this issue.

Here's code to do it (graph is g):

g_distance_dict = {(e1, e2): 1 / weight for e1, e2, weight in g.edges(data='weight')}
nx.set_edge_attributes(g, g_distance_dict, 'distance')

Upvotes: 4

jjrr
jjrr

Reputation: 1148

It was easy:

instead of using nx.degree_centrality() I use my_graph.degree(weight='weight') - still I think this is a basic lack in the module...

...but, the issue is still open for nx.closeness_centrality

Upvotes: 5

Related Questions