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 graphG
comprised of thenodes_of_interest
and their neighbors.- In the first
for
loop, iterate overnodes_of_interest
and append the current noden
tonodes_to_draw
. - In the second
for
loop, iterate over the neighbors ofn
, and append all the neighborsnbr
tonodes_to_draw
.
- In the first
- Use the function to extract the subgraph from
T
comprised 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_draw
to 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()