隨時間繪製貼文數量變化
我們來複習如何從圖形資料繪製會隨時間演變的圖統計量。首先,你會使用圖形資料來計算在長度為 td 天的分段時間窗內出現的邊數;在下列練習中,td 為 2 天。
已為你提供 datetime 變數 dayone 與 lastday。
本練習屬於課程
Python 網路分析進階
練習說明
- 使用
timedelta()函式並指定days參數,定義一個為期 2 天的時間差。 - 在
while迴圈內:- 篩選位於滑動時間窗內的邊。請使用串列生成式完成:輸出表達式為
(u, v, d),可迭代物為G.edges(data=True),並包含兩個條件:當d['date']>=curr_day且<curr_day+td。 - 將邊的數量(可用
len()協助計算)加入n_posts。 - 將
curr_day以時間差td遞增。
- 篩選位於滑動時間窗內的邊。請使用串列生成式完成:輸出表達式為
- 使用
plt.plot()繪製n_posts的圖表。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import necessary modules
from datetime import timedelta
import matplotlib.pyplot as plt
# Define current day and timedelta of 2 days
curr_day = dayone
td = ____
# Initialize an empty list of posts by day
n_posts = []
while curr_day < lastday:
if curr_day.day == 1:
print(curr_day)
# Filter edges such that they are within the sliding time window: edges
edges = [(____, ____, ____) for u, v, d in ____ if d['date'] >= ____ and d['date'] < ____ + ____]
# Append number of edges to the n_posts list
____
# Increment the curr_day by the time delta
____ += ____
# Create the plot
plt.plot(____)
plt.xlabel('Days elapsed')
plt.ylabel('Number of posts')
plt.show()