将绘图代码中的图例标签与缺失的线条对应起来,并将该线条添加到图例中。例如:
import matplotlib.pyplot as plt
# 绘图代码
fig, ax = plt.subplots()
line1, = ax.plot([1, 2, 3], [1, 2, 3], label="Line 1")
line2, = ax.plot([1, 2, 3], [3, 2, 1], label="Line 2")
ax.legend()
# 保存图像
fig.savefig("my_plot.png")
# 重新读取图像并显示图例
fig2, ax2 = plt.subplots()
image = plt.imread("my_plot.png")
ax2.imshow(image)
ax2.axis("off")
legend = ax2.legend(handles=[line1, line2])
fig2.show()
这段代码中,我们首先在绘图代码中为每条线条添加了标签,并将它们加入到了图例中。在保存图像后,我们使用 plt.imread()
函数重新读取图像,并在新的图像上显示图例。通过将每条线条的'句柄”(即返回值)传递给新的图例对象,我们可以确保每条线条都在图例中正确地显示。