- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Text alignment in a Matplotlib legend
- Automated legend creation in Matplotlib
- Matplotlib savefig with a legend outside the plot
- How to create a draggable legend in Matplotlib?
- Legend with vertical line in matplotlib
- How to change the legend fontname in Matplotlib?
- Styling a part of label in legend in Matplotlib
- How to adjust the size of a Matplotlib legend box?
- Add a legend in a 3D scatterplot with scatter() in Matplotlib
- Specifying the line width of the legend frame in Matplotlib
- Manually add legend Items Python Matplotlib
- Matplotlib histogram with multiple legend entries
- How to create a legend for a 3D bar in Matplotlib?
- How to add titles to the legend rows in Matplotlib?
- How to add legend to imshow() in Matplotlib?

Advertisements