How to place legend outside of the Plot in Matplotlib?
×


How to place legend outside of the Plot in Matplotlib?

1398

Introduction

When creating plots with Matplotlib in Python, placing the legend outside the plot area can enhance the clarity of your visualizations, especially when dealing with multiple data series. This approach prevents the legend from overlapping with the plot elements, ensuring that all information is presented cleanly.

Why Place the Legend Outside the Plot?

By default, Matplotlib places the legend inside the plot area, which can sometimes obscure data points or clutter the visualization. Moving the legend outside the plot allows for more space within the plot itself and can make the figure more readable, especially when dealing with complex datasets.

How to Position the Legend Outside the Plot

Matplotlib provides the bbox_to_anchor parameter in the legend() function to control the positioning of the legend. This parameter allows you to specify the location of the legend relative to the axes or figure.

Step-by-Step Example

Here's how you can place the legend outside the plot:

import matplotlib.pyplot as plt
import numpy as np

# Create some data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create a plot
plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')

# Place the legend outside the plot
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')

# Adjust layout to make room for the legend
plt.tight_layout()

# Show the plot
plt.show()

Customizing the Legend Position

The bbox_to_anchor parameter accepts a tuple of two values: the x and y coordinates. These values are relative to the axes or figure, depending on the loc parameter. For example:

  • loc='upper left', bbox_to_anchor=(1.05, 1): Places the legend to the right of the plot.
  • loc='upper center', bbox_to_anchor=(0.5, 1.05): Places the legend above the plot.
  • loc='lower right', bbox_to_anchor=(1.05, 0): Places the legend below the plot.

Handling Multiple Subplots

When working with multiple subplots, you can add a shared legend for the entire figure using the fig.legend() function. This method collects handles and labels from all axes and places a single legend outside the plot area.

fig, axs = plt.subplots(2, 2)

# Plot data on each subplot
for ax in axs.flat:
    ax.plot(x, y1, label='sin(x)')
    ax.plot(x, y2, label='cos(x)')

# Add a shared legend
fig.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=2)

# Adjust layout
plt.tight_layout()

# Show the plot
plt.show()

Conclusion

Placing the legend outside the plot in Matplotlib is a simple yet effective way to improve the readability of your visualizations. By using the bbox_to_anchor parameter, you can precisely control the legend's position, ensuring that your data is presented clearly and professionally.


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