如何在 Matplotlib 中切換軸?


若要在 matplotlib 中切換軸,我們可以建立一個圖形並使用 subplots() 方法新增兩個子圖。繪製曲線,提取 x 和 y 資料,並在第二條繪製的曲線上設定這些資料。

步驟

  • 使用 numpy 建立 x 和 y 資料點。

  • 建立一個圖形並新增一套兩個子圖。

  • 設定兩個軸上的圖示題。

  • 使用 plot() 方法繪製 x 和 y 資料點。

  • 使用 get_xdata get_ydata 提取 x 和 y 資料點。

  • 若要切換圖的軸,請將 axis 1 曲線的 x_data y_data 設定為 axis 2 曲線。

  • 調整子圖之間和周圍的填充。

  • 若要展示圖形,請使用 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.show()

輸出

更新於: 12-May-2021

7K+ 次瀏覽

開啟你的 職業生涯

完成該課程獲取認證

開始
廣告