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

การตั้งค่าความยาวหน่วยของแกนใน Matplotlib

ใช้ xlim และ ylim คูณด้วย Scale Factor เพื่อขยาย/ย่อความยาวหน่วยของแกน

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้างข้อมูล X, Y
  3. Plot ข้อมูล
  4. ดึง Limit ปัจจุบันด้วย plt.xlim(), plt.ylim()
  5. คูณด้วย Scale Factor และตั้งค่าใหม่
  6. แสดงผล

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


import matplotlib.pyplot as plt
import numpy as np

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

x = np.linspace(1, 10, 100)
y = np.log(x)

plt.plot(x, y)

axis_scale = 2  # ขยาย 2 เท่า

xmin, xmax = plt.xlim()
ymin, ymax = plt.ylim()

plt.xlim(xmin * axis_scale, xmax * axis_scale)
plt.ylim(ymin * axis_scale, ymax * axis_scale)

plt.show()

วิธีอื่น: ใช้ set_aspect


# ทำให้ 1 หน่วย X = 1 หน่วย Y (Square)
ax.set_aspect('equal')

# กำหนด Ratio เฉพาะ
ax.set_aspect(2)  # 1 หน่วย Y = 2 หน่วย X

การใช้ Data Coordinates vs Axes Coordinates


# Data Coordinates (ค่าเดิม)
ax.set_xlim(0, 10)

# Axes Coordinates (0-1 แทน % ของ Axes)
ax.set_xlim(0, 1)  # ใน transform=ax.transAxes

ผลลัพธ์

กราฟ Log(x) ที่ขยายขอบเขตแกน X และ Y เป็น 2 เท่าของเดิม ทำให้กราฟดู "ยุบ" ลง