在 Matplotlib 中将图例作为单独的图片获取
matplotlibserver side programmingprogramming更新于 2025/5/5 18:22:17
要将图例作为单独的图片获取,我们可以采取以下步骤 −
使用 numpy 创建 x 和 y 点。
使用 figure() 方法,为线图和图例图创建新图形或激活现有图形。
添加 '~.axes.Axes'以子图排列的形式添加到图形中,使用 nrow=1、ncols=1 和 index=1 处的 add_subplot() 方法。
使用 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')