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

วิธีเปลี่ยนช่วงแกน X และ Y ใน Matplotlib

การกำหนดช่วงแกน X และ Y แบบ Manual

ใช้ xlim() และ ylim() กำหนดขอบเขตการแสดงผล

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • สร้างข้อมูล x, y ด้วย numpy
  • พล็อตข้อมูล
  • ตั้งค่า plt.xlim(-10, 10) และ plt.ylim(-1, 1)
  • แสดงผลด้วย 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.linspace(-15, 15, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xlim(-10, 10)
plt.ylim(-1, 1)
plt.show()

คำอธิบาย

  • xlim/ylim รับค่า (min, max) หรือ tuple
  • ข้อมูลนอกช่วงจะไม่แสดง (clipped)
  • ใช้ ax.set_xlim()/set_ylim() ใน OO interface