開始使用免費開始

隨時間繪製貼文數量變化

我們來複習如何從圖形資料繪製會隨時間演變的圖統計量。首先,你會使用圖形資料來計算在長度為 td 天的分段時間窗內出現的邊數;在下列練習中,td 為 2 天。

已為你提供 datetime 變數 dayonelastday

本練習屬於課程

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