ในการเลื่อนแกน X ใน Matplotlib ระหว่าง real-time plot เราสามารถทำตามขั้นตอนต่อไปนี้:
- ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
- สร้าง figure และชุด subplots
- สร้างจุดข้อมูล x และ y ด้วย numpy
- พลอต x และ y ด้วยเมธอด plot()
- สร้าง animation โดยการเรียกฟังก์ชัน *animate* ซ้ำๆ ที่เลื่อนแกน X ระหว่าง real-time plot
- เพื่อแสดงรูป ใช้เมธอด show()
ตัวอย่าง
import matplotlib.pylab as plt
import matplotlib.animation as animation
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
x = np.linspace(0, 15, 100)
y = np.cos(x)
ax.plot(x, y, lw=2, color='red')
def animate(frame):
ax.set_xlim(left=0, right=frame)
ani = animation.FuncAnimation(fig, animate, frames=10)
plt.show()
ผลลัพธ์
