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

วิธีหมุน Axes (Coordinate System) ใน Matplotlib

ภาพรวม

การหมุน axes ทั้งระบบพิกัด (ไม่ใช่แค่ข้อความ) ต้องใช้ Affine2D transform และ floating_axes จาก mpl_toolkits.axisartist

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

  • Import: matplotlib.pyplot, Affine2D, floating_axes
  • กำหนดขนาดฟิกเกอร์
  • สร้าง figure
  • กำหนดขอบเขต axes: scales = (xmin, xmax, ymin, ymax)
  • สร้าง transform: Affine2D().rotate_deg(25)
  • สร้าง GridHelperCurveLinear ด้วย transform และ scales
  • สร้าง FloatingSubplot และเพิ่มลง figure
  • แสดงผล

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

import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist.floating_axes as floating_axes

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

fig = plt.figure()
scales = (0, 5, 0, 5)

t = Affine2D().rotate_deg(25)
h = floating_axes.GridHelperCurveLinear(t, scales)
ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=h)
fig.add_subplot(ax)

plt.show()

ผลลัพธ์

ระบบพิกัดหมุน 25 องศา พร้อม grid lines ที่โค้งตามการหมุน

วิธีหมุน Axes (Coordinate System) ใน Matplotlib

คำอธิบาย

  • Affine2D – affine transformation 2D (rotate, scale, translate, skew)
  • rotate_deg(25) – หมุน 25 องศา
  • GridHelperCurveLinear – ช่วยสร้าง grid lines บน coordinate system ที่โค้ง/หมุน
  • FloatingSubplot – subplot ที่รองรับ curved coordinates
  • ใช้กรณีพิเศษ เช่น polar-like plots, skewed coordinates