สลับแกน x และ y ของกราฟ
ดึงข้อมูล x, y จาก curve แล้วเซ็ตกลับกันใน curve ใหม่
ขั้นตอน
- สร้างข้อมูล x, y ด้วย NumPy
- สร้าง figure และ 2 subplots
- ตั้งค่า title ทั้งสอง axes
- วาดกราฟ x, y ด้วย plot()
- ดึงข้อมูลด้วย get_xdata() และ get_ydata()
- สลับแกน: set_xdata(newy), set_ydata(newx)
- ปรับ layout ด้วย tight_layout()
- แสดงด้วย show()
ตัวอย่างโค้ด
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 50)
y = np.sin(x)
f, axes = plt.subplots(2)
axes[0].set_title("First plot on axis")
curve, = axes[0].plot(x, y, c='r')
newx = curve.get_xdata()
newy = curve.get_ydata()
axes[1].set_title("Switch of first plot")
curve2, = axes[1].plot(x, y, c='r')
curve2.set_xdata(newy)
curve2.set_ydata(newx)
plt.tight_layout()
plt.show()
ผลลัพธ์
