Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Matplotlib - เลื่อนกราฟตามแกน X (Shift Graph)

เลื่อนกราฟตามแกน X โดย Plot เส้นเดิม และเส้นที่เลื่อน (Shift X Values) พร้อม Legend

ตัวอย่างโค้ด

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-5, 5, 100)
y = np.sin(x)

# Original graph
plt.plot(x, y, label='Original Graph')

# Shifted graph: X starts at 1, 2, 3... (same Y values)
plt.plot(range(1, 1 + len(y)), y, label='Shifted Graph')

plt.legend(loc='upper right')
plt.show()

คำอธิบาย

  • เส้นต้นฉบับ: X = -5 ถึง 5 (100 จุด)
  • เส้นเลื่อน: X = 1 ถึง 100 (Index-based), Y ค่าเดิม
  • range(1, 1+len(y)) สร้าง Sequence 1,2,3...,100
  • plt.legend() แสดง Legend ตาม Label
  • ใช้เปรียบเทียบ Pattern ของ Signal ก่อน/หลัง Shift