search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Outline
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Adding a single legend to subplots in Matplotlib

schedule Aug 10, 2023
Last updated
local_offer
PythonMatplotlib
Tags
tocTable of Contents
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
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-plots
fig.subplots_adjust(wspace=0.5, top=0.8)
fig.suptitle("Main Title", fontsize=15)

# Add the subplots
ax1 = 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.

robocat
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
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!