如何在 Matplotlib 使用兩個 Y 軸(兩個單位)繪製單一資料?


要在 Matplotlib 中使用兩個 Y 軸(兩個單位)繪製單一資料,我們可以採取以下步驟 −

  • 設定圖表大小並調整子圖與周圍的填充。
  • 使用 numpy 建立速度加速度資料點。
  • 將子圖新增到當前圖表中。
  • 使用plot()方法繪製速度資料點。
  • 建立一個與 X 軸共享的雙軸。
  • 使用plot()方法繪製加速資料點。
  • 在圖表中放置圖例。
  • 要顯示圖表,請使用show()方法。

示例

import matplotlib.pyplot as plt
import numpy as np

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

speed = np.array([3, 1, 2, 0, 5])
acceleration = np.array([6, 5, 7, 1, 5])

ax1 = plt.subplot()
l1, = ax1.plot(speed, color='red')
ax2 = ax1.twinx()
l2, = ax2.plot(acceleration, color='orange')

plt.legend([l1, l2], ["speed", "acceleration"])

plt.show()

輸出

更新於: 10-6-2021

10K+ 瀏覽量

開啟您的職業生涯

參加課程認證

入門
廣告
© . All rights reserved.