如何將兩個現有的 Matplotlib 圖表合併到一張圖表中?


要將兩個現有的 matplotlib 圖表合併到一張圖表中,可以採取以下步驟 -

  • 設定圖表的尺寸並調整子圖表之間和周圍的邊距。
  • 使用 numpy 建立 x, y1 和 y2 資料點。
  • 使用 plot() 方法繪製 (x, y1) 和 (x, y2) 點。
  • 獲取當前軸線的 xy 資料點。
  • 使用 argsort() 返回將對陣列排序的索引。
  • 追加每個圖表的 x 和 y 資料點。
  • 在第二個索引的子圖表中繪製 X 和 Y 資料點。
  • 要顯示圖表,請使用 show() 方法。

示例

import numpy as np
import matplotlib.pyplot as plt

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

x = np.linspace(-10, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.subplot(211)
plt.plot(x, y1, color='red', lw=5)
plt.plot(x, y2, color='orange', lw=7)

X, Y = [], []

for lines in plt.gca().get_lines():
   for x, y in lines.get_xydata():
      X.append(x)
      Y.append(y)

idx = np.argsort(X)
X = np.array(X)[idx]
Y = np.array(Y)[idx]

plt.subplot(212)

plt.plot(X, Y, color='green', lw=0.75)

plt.show()

輸出

更新時間: 2021-08-04

15 千+ 瀏覽次數

開啟你的 職業生涯

完成課程獲得認證

入門
廣告
© . All rights reserved.