開始使用免費開始

Subgraphs 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()
編輯並執行程式碼