Ego Graph in NetworkX

Viewed 4017

I have bipartite graph with nodes such as(a1,a2,...a100, m1,m2,...). I want to find the induced subgraph for certain nodes say(a1,a2 and a10). I can do this by using networkx.ego_graph, but it takes one vertex at one time and returns the induced graph. I want to know if there is any way to do this at once for all the nodes that i am interested in and then select the one that is largest.

1 Answers

For the general case, the ego graph can be obtained using nx.ego_graph.

Though in your specific case, it looks like you want to find the largest induced ego graph in the network. For that you can first find the node with a highest degree, and then obtain its ego graph.


Let's create an example bipartite graph:

import networkx as nx

B = nx.Graph()
B.add_nodes_from([1, 2, 3, 4, 5, 6], bipartite=0)
B.add_nodes_from(['a', 'b', 'c', 'j', 'k'], bipartite=1)
B.add_edges_from([(1, 'a'), (1, 'b'), (2, 'b'), (2, 'c'), (3, 'c'), (4, 'a'), 
                  (2, 'b'), (3, 'a'), (5, 'k'), (6, 'k'), (6, 'j')])


rcParams['figure.figsize'] = 12, 6
nx.draw(B, node_color='lightblue', 
        with_labels=True)

enter image description here

And as mentioned in the question, say we want to select among the following list of nodes:

l = [1,'a',6]

It looks like you want to select the one that has the highest centrality degree among these. For that you could do:

deg_l = {i:B.degree(i) for i in l}    
highest_centrality_node = max(deg_l.items(), key=lambda x: x[1])[0]

Now we could plot the corresponding ego_graph with:

ego_g = nx.ego_graph(B, highest_centrality_node)
d = dict(ego_g.degree)
nx.draw(ego_g, node_color='lightblue', 
        with_labels=True, 
        nodelist=d, 
        node_size=[d[k]*300 for k in d])

enter image description here

Related