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

พล็อตจำนวนการเปลี่ยนแปลง edge ตามเวลา

ถึงเวลาสร้างกราฟแล้ว! list ทั้งหมดที่สร้างไว้ก่อนหน้านี้ถูกโหลดมาให้ในแบบฝึกหัดนี้แล้ว ไม่ต้องกังวลกับโค้ด matplotlib บางส่วนที่ดูซับซ้อน เพราะมีคอมเมนต์อธิบายไว้ให้เข้าใจได้

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

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

ดูคอร์ส

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

  • พล็อตจำนวน edge ที่เพิ่มขึ้นตามเวลา โดยทำตามขั้นตอนต่อไปนี้:
    • ใช้ list comprehension วนซ้ำผ่าน added เพื่อสร้าง list ชื่อ edges_added โดย output expression ของ list comprehension คือ len(g.edges()) ซึ่ง g คือตัวแปรที่ใช้วนซ้ำ
    • ส่ง list edges_added ให้กับ ax1.plot()
  • พล็อตจำนวน edge ที่ถูกลบออกตามเวลา โดยใช้ list comprehension อีกครั้ง คราวนี้วนซ้ำผ่าน removed แทน added
  • พล็อต fractional changes ตามเวลา โดยส่งเป็นอาร์กิวเมนต์ให้กับ ax2.plot()

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

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

# Import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)

# Plot the number of edges added over time
edges_added = [____(____) for ____ in ____]
plot1 = ax1.plot(____, label='added', color='orange')

# Plot the number of edges removed over time
edges_removed = [____(____) for ____ in ____]
plot2 = ax1.plot(____, label='removed', color='purple')

# Set yscale to logarithmic scale
ax1.set_yscale('log')  
ax1.legend()

# 2nd axes shares x-axis with 1st axes object
ax2 = ax1.twinx()

# Plot the fractional changes over time
plot3 = ax2.plot(____, label='fractional change', color='green')

# Here, we create a single legend for both plots
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines1 + lines2, labels1 + labels2, loc=0)
plt.axhline(0, color='green', linestyle='--')
plt.show()
แก้ไขและรันโค้ด