如何透過 matplotlib.pyplot 儲存圖片?


要使用 matplotlib.pyplot.savefig() 儲存圖片,我們可以按以下步驟進行 -

  • 設定圖片尺寸並調整子圖之間和周圍的邊距。
  • 使用 numpy 建立 x 和 y 資料點。
  • 使用 plot() 方法繪製 x 和 y 資料點。
  • 要儲存圖片,請使用 savefig() 方法。

示例

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(-np.pi, np.pi, 100)

plt.plot(x, np.sin(x) * x, c='red')

plt.savefig("myimage.png")

輸出

當我們執行程式碼時,它將以下圖片作為 "myimage.png" 儲存到專案目錄中。

更新時間:03-Aug-2021

5 千次瀏覽

開啟你的職業生涯

完成課程,獲取認證

開始
廣告
© . All rights reserved.