視覺化連通度
在這裡,你要視覺化觀察「連通度最高的節點」隨時間的變化。上一個練習中產生的最高連通度清單 top_connected 已經載入。
還記得你在第 1 章用過的 defaultdict 嗎?這題你會再用到 defaultdict!就像 Eric 在影片中提到的,這裡偏好使用 defaultdict,因為如果使用一般的 Python 字典,在你嘗試以不存在於字典中的鍵來取值時,會丟出 KeyError。
這題會用到巢狀的 for 迴圈,也就是在一個 for 迴圈裡再放入另一個 for 迴圈。
本練習屬於課程
Python 網路分析進階
練習說明
- 初始化一個空清單的
defaultdict,命名為connectivity。 - 使用
for迴圈迭代top_connected。在這個外層for迴圈的本體中,再次迭代Gs。在這個巢狀迴圈中:connectivity的鍵應是top_connected中的節點n,值則為連通度分數的清單。因此,你需要將len(list(G.neighbors(n)))加到connectivity[n]。
- 使用
.items()迭代connectivity,並將conn傳入plt.plot(),繪製每個節點的連通度。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import necessary modules
import matplotlib.pyplot as plt
from collections import defaultdict
# Create a defaultdict in which the keys are nodes and the values are a list of connectivity scores over time
connectivity = ____
for n in ____:
for g in ____:
connectivity[____].____(len(____))
# Plot the connectivity for each node
fig = plt.figure()
for n, conn in ____:
plt.plot(____, label=n)
plt.legend()
plt.show()