เพื่อพลอตข้อมูลชุดเดียวแต่แสดงด้วยแกน Y สองแกน (หน่วยต่างกัน) ใน Matplotlib
- ตั้งค่าขนาดรูปและ padding ระหว่าง subplots
- สร้างข้อมูล speed และ acceleration ด้วย numpy
- เพิ่ม subplot ให้กับ figure ปัจจุบัน
- พลอต speed ด้วย plot()
- สร้าง twin Axes ที่แบ่งปันแกน X ด้วย twinx()
- พลอต acceleration ด้วย plot()
- วาง legend บน figure
- แสดงรูปด้วย show()
ตัวอย่าง
import matplotlib.pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True speed = np.array([3, 1, 2, 0, 5]) acceleration = np.array([6, 5, 7, 1, 5]) ax1 = plt.subplot() l1, = ax1.plot(speed, color='red') ax2 = ax1.twinx() l2, = ax2.plot(acceleration, color='orange') plt.legend([l1, l2], ["speed", "acceleration"]) plt.show()
ผลลัพธ์
