子圖中的 Matplotlib 圖例


要在子圖中新增圖例,我們可以採取以下步驟 -

  • 使用 numpy,為 x、y1、y2 和 y3 建立點。

  • 建立一個圖形和一組子圖,使用 subplots() 方法,考慮 3 個子圖。

  • 將曲線繪製在所有 subplots(3) 上,並採用不同的標籤和顏色。透過新增標籤放置每個曲線或子圖的圖例。

  • 若要啟用每條曲線的標籤,請使用 legend() 方法。

  • 若要顯示圖形,請使用 show() 方法。

示例

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
f, axes = plt.subplots(3)
axes[0].plot(x, y1, c='r', label="sine")
axes[0].legend(loc='upper left')
axes[1].plot(x, y2, c='g', label="cosine")
axes[1].legend(loc='upper left')
axes[2].plot(x, y3, c='b', label="tan")
axes[2].legend(loc='upper left')
plt.show()

輸出

更新於: 26-Oct-2023

27K+ 瀏覽量

開啟你的 職業生涯

獲得完成課程的認證

開始
廣告