Search code examples
python-3.xgraphnetworkxsnanode-centrality

What is the best way to calculate centralities for a single node in networkx?


I am able to calculate different kinds of centralities such as degree, betweenness, closeness, and eigenvector for all the nodes in graph G. For instance, this code calculates the betweenness centrality for all of the included nodes of graph G:

import networkx as nx
# build up a graph
G = nx.Graph()
G.add_nodes_from(['A', 'B', 'C', 'D', 'E'])
G.add_edges_from([('A', 'B'), ('B','C'), ('C', 'D'), ('D', 'E')])
bw_centrality = nx.betweenness_centrality(G, normalized=True)
print (bw_centrality)

For large networks, it is very time consuming to calculate some of the centralities, such as betweenness and closeness. Therefore, I would like to calculate the centrality of only a subset of nodes, instead of calculating all of the nodes' centrality. In the example above, how can I calculate the betweenness of node A, by Networkx library in Python?


Solution

  • In a graph, I found a solution for calculating the closeness centrality of a single node. But, for betweenness, I have not been able to find a solution. Let's calculate a node's closeness centrality in a graph. Here is how the closeness of all the nodes can be calculated: import networkx as nx

    # build up a graph
    
    G = nx.Graph()
    G.add_nodes_from(['A', 'B', 'C', 'D', 'E'])
    G.add_edges_from([('A', 'B'), ('B','C'), ('C', 'D'), ('D', 'E')])
    cc_centrality = nx.closeness_centrality(G)
    
    print (cc_centrality )
    

    Therefore, the above code produces the following result:

    {'A': 0.4, 'B': 0.5714285714285714, 'C': 0.6666666666666666, 'D': 0.5714285714285714, 'E': 0.4}
    

    In the next step, we will calculate the closeness of node A separately. According to the source code for Neworkx, closeness centrality has the following meaning:

    closeness_centrality(G, u=None, distance=None, wf_improved=True)
    

    The graph G shows the defined graph, and u represents the node you want to determine its closeness separately. To calculate the closeness of node A, follow these steps:

    nx.closeness_centrality(G, u='A')
    

    The result equals to 0.4. Similarly, nx.closeness_centrality(G, u='B') gives you 0.5714285714285714.