How to create a Single Legend for all subplots in Matplotlib
×


How to create a Single Legend for all subplots in Matplotlib

2723

Introduction

When plotting multiple subplots using Matplotlib, having individual legends on each can clutter your figure. A cleaner approach is to create one single legend that represents all the lines or markers across every subplot. This tutorial will show you how to do exactly that in a simple and effective way.

Why Use a Single Legend for All Subplots?

Multiple legends can take up a lot of space and make your visualization harder to read. Combining them into a single, shared legend improves clarity and provides a unified reference for all plotted data series across subplots.

How to Combine Legends from Multiple Subplots

Matplotlib allows you to retrieve legend handles and labels from each subplot individually. By collecting and merging these handles and labels, you can create a consolidated legend for the entire figure.

Step-by-Step Example

Here’s a practical example that demonstrates this approach:

import matplotlib.pyplot as plt

# Create figure and subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))

# Plot data on first subplot
ax1.plot([1, 2, 3], label='Series A')
ax1.plot([3, 2, 1], label='Series B')

# Plot data on second subplot
ax2.plot([1, 3, 2], label='Series A')
ax2.plot([2, 1, 3], label='Series C')

# Get legend handles and labels from both subplots
handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()

# Combine handles and labels, removing duplicates
combined_labels_handles = dict(zip(labels1 + labels2, handles1 + handles2))

# Add a single legend for the entire figure
fig.legend(combined_labels_handles.values(), combined_labels_handles.keys(), loc='upper center', ncol=3)

plt.tight_layout(rect=[0, 0, 1, 0.95])  # Adjust layout to fit legend
plt.show()

Customizing Your Legend

  • Location: Use the loc argument in fig.legend() to position your legend. Popular positions are 'upper center', 'lower right', or you can use coordinates with bbox_to_anchor.
  • Columns: Adjust ncol to spread your legend items horizontally or vertically for better readability.
  • Appearance: Customize fonts, colors, and markers by using additional legend parameters as needed.

Summary

Instead of cluttering your subplots with multiple legends, create one unified legend that clearly represents all the data series across your figure. This method helps keep your plots tidy and easier to understand.


If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat