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
Adding a legend to a Matplotlib boxplot with multiple plots on the same axis
When creating multiple boxplots on the same axis in Matplotlib, adding a legend helps distinguish between different datasets. This is particularly useful when comparing multiple groups or categories of data.
Basic Boxplot with Legend
First, let's create two datasets and plot them with different colors ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample datasets
dataset_a = np.random.normal(10, 2, 100)
dataset_b = np.random.normal(12, 3, 100)
fig = plt.figure()
ax = fig.add_subplot(111)
# Create boxplots with different colors
bp1 = ax.boxplot(dataset_a, positions=[1], notch=True, widths=0.35,
patch_artist=True, boxprops=dict(facecolor="lightblue"))
bp2 = ax.boxplot(dataset_b, positions=[2], notch=True, widths=0.35,
patch_artist=True, boxprops=dict(facecolor="lightcoral"))
# Add legend using the box patches
ax.legend([bp1["boxes"][0], bp2["boxes"][0]],
["Dataset A", "Dataset B"], loc='upper right')
ax.set_xlabel('Datasets')
ax.set_ylabel('Values')
ax.set_title('Multiple Boxplots with Legend')
plt.show()
Multiple Groups Comparison
For comparing multiple groups across different categories, position the boxplots strategically ?
import matplotlib.pyplot as plt
import numpy as np
# Create data for two groups across three categories
group1_data = [np.random.normal(10, 2, 50), np.random.normal(12, 2, 50), np.random.normal(8, 2, 50)]
group2_data = [np.random.normal(11, 2, 50), np.random.normal(10, 2, 50), np.random.normal(9, 2, 50)]
fig, ax = plt.subplots(figsize=(8, 5))
# Positions for the boxplots
positions1 = [1, 3, 5]
positions2 = [1.5, 3.5, 5.5]
# Create boxplots
bp1 = ax.boxplot(group1_data, positions=positions1, widths=0.4,
patch_artist=True, boxprops=dict(facecolor="skyblue"))
bp2 = ax.boxplot(group2_data, positions=positions2, widths=0.4,
patch_artist=True, boxprops=dict(facecolor="orange"))
# Add legend
ax.legend([bp1["boxes"][0], bp2["boxes"][0]],
["Group 1", "Group 2"], loc='upper left')
# Customize the plot
ax.set_xticks([1.25, 3.25, 5.25])
ax.set_xticklabels(['Category A', 'Category B', 'Category C'])
ax.set_ylabel('Values')
ax.set_title('Grouped Boxplots Comparison')
plt.tight_layout()
plt.show()
Advanced Legend Customization
You can customize the legend appearance with additional styling options ?
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
data1 = np.random.exponential(2, 100)
data2 = np.random.gamma(2, 2, 100)
data3 = np.random.lognormal(1, 0.5, 100)
fig, ax = plt.subplots(figsize=(9, 6))
# Create boxplots with custom properties
bp1 = ax.boxplot([data1], positions=[1], widths=0.6, patch_artist=True,
boxprops=dict(facecolor="lightgreen", alpha=0.7))
bp2 = ax.boxplot([data2], positions=[2], widths=0.6, patch_artist=True,
boxprops=dict(facecolor="gold", alpha=0.7))
bp3 = ax.boxplot([data3], positions=[3], widths=0.6, patch_artist=True,
boxprops=dict(facecolor="plum", alpha=0.7))
# Create custom legend with styling
legend = ax.legend([bp1["boxes"][0], bp2["boxes"][0], bp3["boxes"][0]],
['Exponential', 'Gamma', 'Log-normal'],
loc='upper right', frameon=True, shadow=True,
fancybox=True, framealpha=0.9)
ax.set_xticks([1, 2, 3])
ax.set_xticklabels(['Exp', 'Gamma', 'LogNorm'])
ax.set_ylabel('Distribution Values')
ax.set_title('Statistical Distributions Comparison')
ax.grid(True, alpha=0.3)
plt.show()
Key Parameters
| Parameter | Description | Example Values |
|---|---|---|
positions |
X-axis positions for boxplots | [1, 2, 3] or [1, 1.5, 2] |
patch_artist |
Enable color filling | True/False |
boxprops |
Box styling properties | dict(facecolor="blue") |
loc |
Legend location | 'upper right', 'lower left' |
Conclusion
Adding legends to matplotlib boxplots requires using patch_artist=True and referencing the box patches in the legend. Position multiple boxplots strategically and customize legend appearance for clear data visualization.
Advertisements
