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()