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

การตั้งค่า Axis Limits ให้เหมือนกันทุกซับพลอตใน Matplotlib

ใช้ plt.subplot() พร้อมพารามิเตอร์ sharex และ sharey อ้างอิงจาก axes แรก ทำให้ทุกซับพลอตมีขอบเขตแกนเท่ากันโดยอัตโนมัติ

ขั้นตอนการทำงาน

  1. ตั้งค่าขนาดรูปและเลย์เอาต์
  2. สร้าง axes แรก ax1 = plt.subplot(2, 2, 1) ตั้ง xlim, ylim
  3. สร้าง axes ต่อไปด้วย sharex=ax1, sharey=ax1
  4. พลอตข้อมูลบนแต่ละ axes
  5. แสดงผล

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

from matplotlib import pyplot as plt

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

ax1 = plt.subplot(2, 2, 1)
ax1.set_xlim(left=0, right=5)
ax1.set_ylim(bottom=0, top=5)
ax1.plot([1, 4, 3])

ax2 = plt.subplot(2, 2, 2, sharey=ax1, sharex=ax1)
ax2.plot([3, 4, 1])

ax3 = plt.subplot(2, 2, 4, sharey=ax1, sharex=ax1)
ax3.plot([2, 4, 2])

ax4 = plt.subplot(2, 2, 3, sharey=ax1, sharex=ax1)
ax4.plot([4, 0, 4])

plt.show()

ผลลัพธ์

การตั้งค่า Axis Limits ให้เหมือนกันทุกซับพลอตใน Matplotlib