Matplotlib
keyboard_arrow_down 83 guides
chevron_leftLegend Cookbook
check_circle
Mark as learned thumb_up
1
thumb_down
0
chat_bubble_outline
0
Comment auto_stories Bi-column layout
settings
Adding a single legend to subplots in Matplotlib
schedule Aug 10, 2023
Last updated local_offer
Tags Python●Matplotlib
tocTable of Contents
expand_more Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!
Start your free 7-days trial now!
To add a single legend to subplots in Matplotlib:
fig = plt.figure(figsize=(5, 2.2))gs = plt.GridSpec(1, 2)
# Needed to add spacing between 1st and 2nd plots# Add a margin between the main title and sub-plotsfig.subplots_adjust(wspace=0.5, top=0.8)fig.suptitle("Main Title", fontsize=15)
# Add the subplotsax1 = fig.add_subplot(gs[0])ax2 = fig.add_subplot(gs[1])ax1.plot(1,2, marker="*", label="my_star")ax2.plot(1,2, marker="*", label="my_star")
handles, labels = ax2.get_legend_handles_labels()fig.legend(handles, labels, loc="upper left", bbox_to_anchor=(0.65,1.05))
plt.figure(figsize=(1,2.5))plt.show()
This produces the output:
We need to use the get_legend_handles_labels()
method on the last axis only. The next line is used to display the legend on the plot. The bbox_to_anchor
parameter is used to shift offset the legend so that it appears in the top right corner.
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!