开始使用免费开始使用

子图 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()
编辑并运行代码