子图 I
有时您只想分析网络中的一部分节点。为此,您可以使用 G.subgraph(nodes) 将它们复制到另一个图对象中。该方法会返回一个新的 graph 对象(类型与原图相同),其中仅包含传入的可迭代对象 nodes 所指定的节点组成的子图。
matplotlib.pyplot 已为您导入为 plt。
本练习是课程的一部分
Python 网络分析入门
练习说明
- 编写函数
get_nodes_and_nbrs(G, nodes_of_interest),从图G中提取由nodes_of_interest及其邻居组成的子图。- 在第一个
for循环中,遍历nodes_of_interest,并将当前节点n追加到nodes_to_draw。 - 在第二个
for循环中,遍历n的所有邻居,并将每个邻居nbr追加到nodes_to_draw。
- 在第一个
- 使用该函数从
T中提取由节点 29、38 和 42(已在预定义列表nodes_of_interest中)及其邻居组成的子图。将结果保存为T_draw。 - 将子图
T_draw绘制到屏幕上。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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()