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

Matplotlib Axes Object คืออะไร?

Axes Object เป็นส่วนประกอบหลักของ Figure ประกอบไปด้วย Axis, Tick, Line2D, Text, Polygon และตั้งค่าระบบพิกัด

องค์ประกอบของ Axes

  • Axis: แกน X และ Y (Spines, Ticks, Labels)
  • Spines: เส้นขอบกราฟ (top, bottom, left, right)
  • Ticks: ตัวชี้วัดบนแกน
  • Labels: ข้อความอธิบายแกน
  • Title: หัวข้อกราฟ
  • Legend: คำอธิบายสัญลักษณ์
  • Artists: Line2D, Text, Patch, Collection, Image, etc.

ตัวอย่าง: การเข้าถึงและปรับ Spines


from matplotlib import pyplot as plt

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

plt.rcParams['axes.linewidth'] = 5

# สร้าง Axes
ax = plt.axes()

# ปรับสี Spines แต่ละด้าน
ax.spines['bottom'].set_color('yellow')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('black')
ax.spines['left'].set_color('blue')

# ปรับความหนา Spines
for spine in ax.spines.values():
    spine.set_linewidth(3)

plt.show()

การเข้าถึง Axes แบบต่างๆ


# Stateful (pyplot)
plt.plot([1,2,3])
ax = plt.gca()  # Get Current Axes

# Object-Oriented (แนะนำ)
fig, ax = plt.subplots()
ax.plot([1,2,3])

# Multiple Axes
fig, axes = plt.subplots(2, 2)
ax1 = axes[0, 0]
ax2 = axes.flat[1]

ผลลัพธ์

กราฟว่างเปล่า แต่ Spines 4 ด้านมีสีต่างกัน: ล่าง=เหลือง, บน=แดง, ขวา=ดำ, ซ้าย=น้ำเงิน