Matplotlib,帶圖例儲存的圖形位於圖形外部


要以在圖形外部放置圖例的方式儲存檔案,我們可以採取以下步驟:

  • 使用 numpy 建立 資料點。

  • 使用 plot() 方法繪製 y=sin(x) 曲線,使用 color=redmarker="v" 和標籤 y=sin(x)

  • 使用 plot() 方法繪製 y=cos(x) 曲線,使用 color=greenmarker="x" 和標籤 y=cos(x)

  • 要將圖例放置在圖形外部,請使用 bbox_to_anchor(.45, 1.15) 和 location="upper center"。

  • 要儲存該圖形,請使用 savefig() 方法。

示例

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, 100)
plt.plot(x, np.sin(x), c="red", marker="v", label="y=sin(x)")
plt.plot(x, np.cos(x), c="green", marker="x", label="y=cos(x)")
plt.legend(bbox_to_anchor=(.45, 1.15), loc="upper center")
plt.savefig("legend_outside.png")

輸出

執行此程式碼後,它會以“legend_outside.png”為名稱將以下圖形儲存到當前目錄中。

更新於: 2021 年 5 月 6 日

2K+ 瀏覽

開啟您的職業生涯

修完課程即可獲得認證

開始學習
廣告
© . All rights reserved.