ภาพรวม
ใช้ twinx() (แบ่งแกน Y) หรือ twiny() (แบ่งแกน X) เพื่อพลอตข้อมูลที่มี Scale ต่างกันบนแกนร่วม
ขั้นตอน (twinx - แบ่งแกน Y)
- สร้าง Figure และ Axes ด้วย
plt.subplots() - พลอตข้อมูลชุดแรกบน Axes เดิม (แกน Y ซ้าย)
- สร้าง Twin Axes ด้วย
ax1.twinx()(แกน Y ขวา) - พลอตข้อมูลชุดที่สองบน Twin Axes
- ปรับ 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