Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách đổi chỗ trục X và Y trong Matplotlib

Hoán đổi trục bằng cách lấy get_xdata(), get_ydata() từ curve1 và gán ngược cho curve2.

  • Tạo x, y = sin(x).
  • fig, axes = subplots(2).
  • axes[0].plot(x, y, c='r') → curve.
  • newx = curve.get_xdata(), newy = curve.get_ydata().
  • axes[1].plot(x, y, c='r') → curve2.
  • curve2.set_xdata(newy), curve2.set_ydata(newx).
  • show().

Ví dụ

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.show()

Kết quả

Trên: y = sin(x). Dưới: x = sin(y) (trục hoán đổi).