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

วิธีพลอตหลายแกน X หรือ Y ใน Matplotlib


ภาพรวม

ใช้ twinx() (แบ่งแกน Y) หรือ twiny() (แบ่งแกน X) เพื่อพลอตข้อมูลที่มี Scale ต่างกันบนแกนร่วม

ขั้นตอน (twinx - แบ่งแกน Y)

  1. สร้าง Figure และ Axes ด้วย plt.subplots()
  2. พลอตข้อมูลชุดแรกบน Axes เดิม (แกน Y ซ้าย)
  3. สร้าง Twin Axes ด้วย ax1.twinx() (แกน Y ขวา)
  4. พลอตข้อมูลชุดที่สองบน Twin Axes
  5. ปรับ Layout และแสดงผล

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

import matplotlib.pyplot as plt

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

fig, ax1 = plt.subplots()
ax1.plot([1, 2, 3, 4, 5], color='red')
ax1.set_ylabel('Left Y', color='red')

ax2 = ax1.twinx()
ax2.plot([11, 12, 31, 41, 15], color='blue')
ax2.set_ylabel('Right Y', color='blue')

fig.tight_layout()
plt.show()

ผลลัพธ์

กราฟเดียวมี 2 แกน Y: ซ้าย (สีแดง) และ ขวา (สีน้ำเงิน) แบ่งแกน X ร่วมกัน

สำหรับ Twiny (แบ่งแกน X)

ax2 = ax1.twiny()  # แบ่งแกน X บน
ax2.plot(y_data, x_data)  # สลับ X, Y