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.
Asked
Active
Viewed 4,741 times
8
-
Thanks @yatu. This does work correctly. I made a small change to suite my requirements. The Solution looks for highest degree, but i wanted to get the number of nodes in the largest connected component involving nodes in a list say (l = [1,'a',6]]) and there may be other nodes as well connected to these that I have to consider. So i created ego graph for each node in the list and then used Graph.Compose_all to create a subgraph. Then i used the connected_components on the composed graph to get the one with largest length. – ankshukla Apr 01 '20 at 10:19
-
Sounds like the right approach. Glad it helped :) – yatu Apr 01 '20 at 10:23
-
This was exactly I was looking for since last two days and helped me. – asspsss May 19 '20 at 21:22
1 Answers
6
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)
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])

yatu
- 86,083
- 12
- 84
- 139