เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

พล็อตจำนวนโพสต์ที่เกิดขึ้นตามช่วงเวลา

มาทบทวนวิธีพล็อตสถิติของกราฟที่เปลี่ยนแปลงตามเวลากัน โดยจะใช้ข้อมูลกราฟเพื่อนับจำนวน edge ที่ปรากฏภายในหน้าต่างเวลาขนาด td วัน ซึ่งในแบบฝึกหัดนี้กำหนดไว้ที่ 2 วัน

ตัวแปร datetime ชื่อ dayone และ lastday ได้เตรียมไว้ให้แล้ว

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การวิเคราะห์เครือข่ายระดับกลางใน Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • กำหนด timedelta เป็น 2 วัน โดยใช้ฟังก์ชัน timedelta() และระบุอาร์กิวเมนต์สำหรับพารามิเตอร์ days
  • ภายใน while loop:
    • กรอง edge ที่อยู่ภายในหน้าต่างเวลาแบบเลื่อน โดยใช้ list comprehension ที่มีนิพจน์ผลลัพธ์เป็น (u, v, d) วนซ้ำผ่าน G.edges(data=True) และมีสองเงื่อนไข: d['date'] ต้อง >= curr_day และ < กว่า curr_day + td
    • เพิ่มจำนวน edge (ใช้ฟังก์ชัน len() ในการคำนวณ) ลงใน n_posts
    • เพิ่มค่า curr_day ด้วย time delta td
  • สร้างกราฟของ n_posts โดยใช้ plt.plot()

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# 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()  
แก้ไขและรันโค้ด