เพื่อหาความยาวของหน่วยเดียวบนแกนใน Matplotlib ให้ทำตามขั้นตอน:
- กำหนดขนาดรูปและปรับระยะห่างระหว่างและรอบซับพล็อต
- สร้างจุดข้อมูล x และ y ด้วย NumPy
- สร้างรูปใหม่หรือเปิดใช้งานรูปที่มีอยู่ด้วย figure()
- เพิ่ม '~.axes.Axes' ลงในรูปเป็นส่วนหนึ่งของการจัดซับพล็อต
- พล็อตจุดข้อมูล x และ y ด้วย plot()
- ใช้การแปลง transData เพื่อหาความยาวหน่วยเดียว
- พิมพ์ความยาวแนวนอนและแนวตั้ง
- ใช้ show() เพื่อแสดงรูป
ตัวอย่าง
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.arange(0, 10, 0.005)
y = np.exp(-x / 2.) * np.sin(2 * np.pi * x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
xy = ax.transData.transform([(0, 1), (1, 0)]) - ax.transData.transform((0, 0))
print("Vertical length:", xy[0][1])
print("Horizontal length:", xy[1][0])
plt.show()ผลลัพธ์

นอกจากกราฟแล้ว จะได้ผลลัพธ์บนคอนโซลดังนี้:
Vertical length: 269.5 Horizontal length: 581.25