แสดงผลกราฟ Random Walk
มาแสดงผล random walk นี้กันเลย! จำได้ไหมว่าใช้ matplotlib สร้าง line plot ได้อย่างไร?
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.show()
ลิสต์แรกที่ส่งเข้าไปจะถูกแมปไปยังแกน x และลิสต์ที่สองจะถูกแมปไปยังแกน y
หากส่งอาร์กิวเมนต์เพียงตัวเดียว Python จะรู้ว่าต้องทำอะไร โดยใช้ index ของลิสต์แมปกับแกน x และใช้ค่าในลิสต์แมปกับแกน y
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python ระดับกลาง
คำแนะนำการฝึกหัด
เพิ่มโค้ดต่อไปนี้หลัง for loop:
- Import
matplotlib.pyplotเป็นplt - ใช้
plt.plot()เพื่อพล็อตกราฟrandom_walk - ปิดท้ายด้วย
plt.show()เพื่อแสดงกราฟออกมา
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# NumPy is imported, seed is set
# Initialization
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
random_walk.append(step)
# Import matplotlib.pyplot as plt
# Plot random_walk
# Show the plot