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

วิธีสลับแกน x และ y ใน Matplotlib


สลับแกน x และ y ของกราฟ

ดึงข้อมูล x, y จาก curve แล้วเซ็ตกลับกันใน curve ใหม่

ขั้นตอน

  1. สร้างข้อมูล x, y ด้วย NumPy
  2. สร้าง figure และ 2 subplots
  3. ตั้งค่า title ทั้งสอง axes
  4. วาดกราฟ x, y ด้วย plot()
  5. ดึงข้อมูลด้วย get_xdata() และ get_ydata()
  6. สลับแกน: set_xdata(newy), set_ydata(newx)
  7. ปรับ layout ด้วย tight_layout()
  8. แสดงด้วย 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()

ผลลัพธ์

วิธีสลับแกน x และ y ใน Matplotlib