Subgraph I
บางครั้งอาจต้องการวิเคราะห์เฉพาะโหนดบางส่วนในเครือข่าย ทำได้โดยคัดลอกโหนดเหล่านั้นออกมาเป็น graph object ใหม่ ด้วยคำสั่ง G.subgraph(nodes) ซึ่งจะคืนค่าเป็น graph object ใหม่ (ชนิดเดียวกับ graph ต้นฉบับ) ที่ประกอบด้วยโหนดจาก iterable ของ nodes ที่ส่งเข้าไป
ได้นำเข้า matplotlib.pyplot ให้แล้วในชื่อ plt
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การวิเคราะห์เครือข่ายเบื้องต้นด้วย Python
คำแนะนำการฝึกหัด
- เขียนฟังก์ชัน
get_nodes_and_nbrs(G, nodes_of_interest)เพื่อดึง subgraph จาก graphGที่ประกอบด้วยnodes_of_interestและ neighbors ของโหนดเหล่านั้น- ในลูป
forแรก ให้วนซ้ำผ่านnodes_of_interestและเพิ่มโหนดปัจจุบันnเข้าไปในnodes_to_draw - ในลูป
forที่สอง ให้วนซ้ำผ่าน neighbors ของnและเพิ่ม neighbor ทุกตัวnbrเข้าไปในnodes_to_draw
- ในลูป
- ใช้ฟังก์ชันนี้เพื่อดึง subgraph จาก
Tที่ประกอบด้วยโหนด 29, 38 และ 42 (ซึ่งอยู่ในลิสต์nodes_of_interestที่กำหนดไว้แล้ว) พร้อมด้วย neighbors ของโหนดเหล่านั้น แล้วบันทึกผลลัพธ์เป็นT_draw - วาด subgraph
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()