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 show legend elements horizontally in Matplotlib?
In Matplotlib, legends are displayed vertically by default. To arrange legend elements horizontally, use the ncol parameter in the legend() method to specify the number of columns.
Basic Horizontal Legend
The ncol parameter controls how many columns the legend should have ?
import matplotlib.pyplot as plt
# Create sample data
x = [1, 2, 3, 4]
y1 = [1, 4, 2, 3]
y2 = [2, 3, 1, 4]
y3 = [3, 1, 4, 2]
# Plot lines with labels
plt.plot(x, y1, label="Series A")
plt.plot(x, y2, label="Series B")
plt.plot(x, y3, label="Series C")
# Create horizontal legend with 3 columns
plt.legend(ncol=3, loc="upper right")
plt.title("Horizontal Legend Example")
plt.show()
Different Legend Positions
You can place horizontal legends at various positions using the loc parameter ?
import matplotlib.pyplot as plt
# Create sample data
x = [1, 2, 3, 4, 5]
y1 = [2, 5, 3, 8, 7]
y2 = [3, 4, 6, 2, 9]
plt.figure(figsize=(8, 6))
plt.plot(x, y1, 'o-', label="Dataset 1")
plt.plot(x, y2, 's-', label="Dataset 2")
# Horizontal legend at the bottom
plt.legend(ncol=2, loc="lower center", bbox_to_anchor=(0.5, -0.1))
plt.title("Legend Positioned Below Plot")
plt.tight_layout()
plt.show()
Customizing Horizontal Legend Spacing
Use columnspacing to adjust spacing between legend columns ?
import matplotlib.pyplot as plt
# Sample data
categories = ['A', 'B', 'C', 'D']
values1 = [23, 45, 56, 78]
values2 = [38, 25, 67, 45]
values3 = [42, 58, 33, 62]
plt.figure(figsize=(10, 6))
plt.plot(categories, values1, 'o-', label="Product X")
plt.plot(categories, values2, 's-', label="Product Y")
plt.plot(categories, values3, '^-', label="Product Z")
# Horizontal legend with custom spacing
plt.legend(ncol=3, loc="upper left", columnspacing=2.0, handletextpad=0.5)
plt.title("Custom Legend Spacing")
plt.grid(True, alpha=0.3)
plt.show()
Legend Parameters
| Parameter | Description | Example |
|---|---|---|
ncol |
Number of columns | ncol=3 |
loc |
Legend position | loc="upper right" |
columnspacing |
Space between columns | columnspacing=2.0 |
bbox_to_anchor |
Custom positioning | bbox_to_anchor=(0.5, -0.1) |
Conclusion
Use ncol parameter in plt.legend() to create horizontal legends. Combine with loc and bbox_to_anchor for precise positioning and spacing control.
Advertisements
