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

วิธีวาดเส้นแกน (Axis Lines) อยู่ภายในพื้นที่พลอตใน Matplotlib

ภาพรวม

ปกติแกน X และ Y จะอยู่ที่ขอบกราฟ สามารถย้ายมาไว้ที่จุดกำเนิด (0,0) ภายในพื้นที่พลอตได้โดยปรับ spines

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

  • กำหนดขนาดฟิกเกอร์
  • สร้าง figure และ axes
  • พลอตข้อมูล (ตัวอย่าง y = x²)
  • ตั้งค่า spines: left และ bottom -> position 'zero', right และ top -> color 'none'
  • แสดงผล

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

import numpy as np
import matplotlib.pyplot as plt

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

fig = plt.figure()
x = np.linspace(-5, 5, 100)
ax = fig.add_subplot(111)
ax.plot(x, x * x)

# Move spines to center (0,0)
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')

# Hide top and right spines
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# Optional: ticks only on left and bottom
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

plt.show()

ผลลัพธ์

กราฟพาราโบล่า แกน X และ Y ตัดกันที่ (0,0) กลางกราฟ

วิธีวาดเส้นแกน (Axis Lines) อยู่ภายในพื้นที่พลอตใน Matplotlib วิธีวาดเส้นแกน (Axis Lines) อยู่ภายในพื้นที่พลอตใน Matplotlib

ตัวเลือกเพิ่มเติม

  • ax.spines['left'].set_position(('data', 0)) ระบุตำแหน่งใน data coordinates
  • ax.spines['left'].set_position(('axes', 0.5)) ระบุใน axes coordinates (0-1)
  • ใช้ ax.axhline(0, color='black') และ ax.axvline(0, color='black') วาดเส้นแกนแทน spines