在 Matplotlib 中獲取單獨的圖片形式的圖例


要將圖例作為單獨的圖片獲取,我們可以採取以下步驟:

  • 使用 Numpy 建立 x 和 y 點。

  • 使用 figure() 方法建立新的圖形,或啟用現有的關於折線圖和圖例圖的圖形。

  • '~.axes.Axes' 作為子圖排列的一部分新增到圖形中,使用add_subplot() 方法在nrow=1ncols=1index=1 處。

  • 使用 x、y 和 y1 點建立line1 line2 

  • 放置line1 line2 的圖例,設定有序標籤,置於中心位置。

  • 僅使用savefig() 方法儲存帶圖例的圖形。

示例

import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(1, 100, 1000)
y = np.log(x)
y1 = np.sin(x)
fig = plt.figure("Line plot")
legendFig = plt.figure("Legend plot")
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, c="red", lw=4, linestyle="dashdot")
line2, = ax.plot(x, y1, c="green", lw=1, linestyle="--")
legendFig.legend([line1, line2], ["y=log(x)", "y=sin(x)"], loc='center')
legendFig.savefig('legend.png')

輸出

更新於:10-4-2021

3K+ 瀏覽

啟動你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.