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

การสร้าง Multiple Overlapping Plots แยก Scaling ด้วย Matplotlib

ใช้ ax.twinx() สร้างแกน Y ที่สอง (Secondary Y-axis) แบบ Shared X-axis เพื่อพล็อตข้อมูลที่มี Scale ต่างกันบนกราฟเดียวกัน

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้าง Figure และ Axes หลัก (ax1)
  3. Plot ข้อมูลชุดแรกบน ax1
  4. สร้าง Twin Axes (ax2) ด้วย ax1.twinx()
  5. Plot ข้อมูลชุดที่สองบน ax2
  6. แสดงผล

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


import matplotlib.pyplot as plt

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

fig, ax1 = plt.subplots()

# ข้อมูลชุดแรก (แกน Y ซ้าย)
ax1.plot([1, 2, 3, 4, 5], color='red')
ax1.set_ylabel('Data 1', color='red')
ax1.tick_params(axis='y', labelcolor='red')

# สร้าง Twin Axes (แกน Y ขวา)
ax2 = ax1.twinx()

# ข้อมูลชุดที่สอง (แกน Y ขวา)
ax2.plot([11, 12, 31, 41, 15], color='blue')
ax2.set_ylabel('Data 2', color='blue')
ax2.tick_params(axis='y', labelcolor='blue')

plt.show()

การเพิ่ม Legend


lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')

ผลลัพธ์

กราฟเดียวมี 2 เส้นข้อมูล: เส้นแดง (Scale 1-5) และเส้นน้ำเงิน (Scale 11-41) แสดงบนแกน Y ต่างกันแต่ใช้แกน X ร่วมกัน