พล็อตจำนวนการเปลี่ยนแปลง edge ตามเวลา
ถึงเวลาสร้างกราฟแล้ว! list ทั้งหมดที่สร้างไว้ก่อนหน้านี้ถูกโหลดมาให้ในแบบฝึกหัดนี้แล้ว ไม่ต้องกังวลกับโค้ด matplotlib บางส่วนที่ดูซับซ้อน เพราะมีคอมเมนต์อธิบายไว้ให้เข้าใจได้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การวิเคราะห์เครือข่ายระดับกลางใน Python
คำแนะนำการฝึกหัด
- พล็อตจำนวน edge ที่เพิ่มขึ้นตามเวลา โดยทำตามขั้นตอนต่อไปนี้:
- ใช้ list comprehension วนซ้ำผ่าน
addedเพื่อสร้าง list ชื่อedges_addedโดย output expression ของ list comprehension คือlen(g.edges())ซึ่งgคือตัวแปรที่ใช้วนซ้ำ - ส่ง list
edges_addedให้กับax1.plot()
- ใช้ list comprehension วนซ้ำผ่าน
- พล็อตจำนวน 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()