Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to put a legend outside the plot with Pandas?
When creating plots with Pandas, legends can sometimes overlap with the plot area. Using bbox_to_anchor parameter in legend() allows you to position the legend outside the plot boundaries for better visibility.
Basic Example
Here's how to create a DataFrame and place the legend outside the plot ?
import pandas as pd
import matplotlib.pyplot as plt
# Set figure size for better display
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample data
data = {'Column 1': [i for i in range(10)],
'Column 2': [i * i for i in range(10)]}
df = pd.DataFrame(data)
# Create plot with different styles
df.plot(style=['o', 'rx'])
# Place legend outside the plot area
plt.legend(bbox_to_anchor=(1.0, 1.0))
plt.show()
Legend Position Options
You can control the legend position using different bbox_to_anchor values ?
import pandas as pd
import matplotlib.pyplot as plt
# Create sample data
data = {'Sales': [100, 150, 120, 180, 200],
'Profit': [20, 30, 25, 40, 50]}
df = pd.DataFrame(data)
# Create subplots to show different legend positions
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
# Top right outside
df.plot(ax=axes[0,0])
axes[0,0].legend(bbox_to_anchor=(1.05, 1), loc='upper left')
axes[0,0].set_title('Legend: Top Right Outside')
# Bottom right outside
df.plot(ax=axes[0,1])
axes[0,1].legend(bbox_to_anchor=(1.05, 0), loc='lower left')
axes[0,1].set_title('Legend: Bottom Right Outside')
# Top center outside
df.plot(ax=axes[1,0])
axes[1,0].legend(bbox_to_anchor=(0.5, 1.05), loc='lower center')
axes[1,0].set_title('Legend: Top Center Outside')
# Bottom center outside
df.plot(ax=axes[1,1])
axes[1,1].legend(bbox_to_anchor=(0.5, -0.05), loc='upper center')
axes[1,1].set_title('Legend: Bottom Center Outside')
plt.tight_layout()
plt.show()
Common bbox_to_anchor Values
| Position | bbox_to_anchor | loc |
|---|---|---|
| Right side | (1.05, 1) | 'upper left' |
| Top outside | (0.5, 1.05) | 'lower center' |
| Bottom outside | (0.5, -0.05) | 'upper center' |
| Left side | (-0.05, 1) | 'upper right' |
Advanced Example with Custom Styling
You can also customize the legend appearance when placing it outside ?
import pandas as pd
import matplotlib.pyplot as plt
# Create sample data
data = {'Q1': [100, 120, 90, 110],
'Q2': [110, 130, 95, 115],
'Q3': [120, 140, 100, 125],
'Q4': [130, 150, 105, 135]}
df = pd.DataFrame(data, index=['Product A', 'Product B', 'Product C', 'Product D'])
# Create the plot
ax = df.plot(kind='bar', figsize=(10, 6))
# Customize legend outside with styling
plt.legend(bbox_to_anchor=(1.05, 1),
loc='upper left',
frameon=True,
fancybox=True,
shadow=True)
plt.title('Quarterly Sales by Product')
plt.ylabel('Sales ($000)')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Key Parameters
Understanding the main parameters for external legend placement:
-
bbox_to_anchor: Tuple specifying the bbox location (x, y coordinates) -
loc: Which part of the legend box the anchor point refers to -
frameon: Whether to draw the legend frame -
fancybox: Whether to use rounded corners -
shadow: Whether to add a shadow effect
Conclusion
Use bbox_to_anchor with appropriate coordinates to place legends outside your Pandas plots. Combine with plt.tight_layout() to ensure proper spacing and prevent legend cutoff.
Advertisements
