Get the legend as a separate picture in Matplotlib

To get the legend as a separate picture, we can take the following steps −

• Create x and y points using numpy.

• Using the figure() method, create a new figure, or activate an existing figure for Line plot and Legend plot figures.

• Add an '~.axes.Axes' to the figure as part of a subplot arrangement, using the add_subplot() method at nrow=1, ncols=1 and at index=1.

• Create line1 and line2 using x, y and y1 points.

• Place the legend for line1 and line2, set ordered labels, put at center location.

• Save the figure only with legend using the savefig() method.

Example

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")
legendFig.savefig('legend.png')