Subgraphs I
There may be times when you just want to analyze a subset of nodes in a network. To do so, you can copy them out into another graph object using G.subgraph(nodes), which returns a new graph object (of the same type as the original graph) that is comprised of the iterable of nodes that was passed in.
matplotlib.pyplot has been imported for you as plt.
This exercise is part of the course
Introduction to Network Analysis in Python
Exercise instructions
- Write a function
get_nodes_and_nbrs(G, nodes_of_interest)that extracts the subgraph from graphGcomprised of thenodes_of_interestand their neighbors.- In the first
forloop, iterate overnodes_of_interestand append the current nodentonodes_to_draw. - In the second
forloop, iterate over the neighbors ofn, and append all the neighborsnbrtonodes_to_draw.
- In the first
- Use the function to extract the subgraph from
Tcomprised of nodes 29, 38, and 42 (contained in the pre-defined listnodes_of_interest) and their neighbors. Save the result asT_draw. - Draw the subgraph
T_drawto the screen.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
nodes_of_interest = [29, 38, 42]
# Define get_nodes_and_nbrs()
def get_nodes_and_nbrs(G, nodes_of_interest):
"""
Returns a subgraph of the graph `G` with only the `nodes_of_interest` and their neighbors.
"""
nodes_to_draw = []
# Iterate over the nodes of interest
for n in ____:
# Append the nodes of interest to nodes_to_draw
____
# Iterate over all the neighbors of node n
for nbr in ____:
# Append the neighbors of n to nodes_to_draw
____
return G.subgraph(nodes_to_draw)
# Extract the subgraph with the nodes of interest: T_draw
T_draw = ____
# Draw the subgraph to the screen
____
plt.show()