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")
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')

Output

Updated on: 10-Apr-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements