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
Creating multiple boxplots on the same graph from a dictionary, using Matplotlib
To create multiple boxplots on the same graph from a dictionary, we can use Matplotlib's boxplot() function. This is useful for comparing distributions of different datasets side by side.
Basic Setup
First, let's understand the steps involved ?
- Set the figure size and adjust the padding between and around the subplots
- Create a dictionary with multiple datasets
- Create a figure and a set of subplots
- Make a box and whisker plot using
boxplot() - Set the x-tick labels using
set_xticklabels()method - Display the figure using
show()method
Example
Here's how to create multiple boxplots from a dictionary ?
import matplotlib.pyplot as plt
# Set figure configuration
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample data dictionary
data = {'Dataset A': [3, 5, 2, 9, 1, 8, 6],
'Dataset B': [2, 6, 1, 3, 4, 7, 5]}
# Create figure and subplot
fig, ax = plt.subplots()
# Create boxplots from dictionary values
ax.boxplot(data.values())
# Set x-axis labels from dictionary keys
ax.set_xticklabels(data.keys())
# Add title and labels
ax.set_title('Multiple Boxplots from Dictionary')
ax.set_ylabel('Values')
plt.show()
Advanced Example with More Datasets
You can also create boxplots with more datasets and customize the appearance ?
import matplotlib.pyplot as plt
import numpy as np
# Create more complex sample data
np.random.seed(42)
data = {
'Group A': np.random.normal(10, 2, 50),
'Group B': np.random.normal(12, 1.5, 50),
'Group C': np.random.normal(8, 3, 50),
'Group D': np.random.normal(15, 2.5, 50)
}
# Create figure
fig, ax = plt.subplots(figsize=(10, 6))
# Create boxplots with customization
box_plot = ax.boxplot(data.values(),
patch_artist=True, # Fill boxes with color
notch=True) # Add notches
# Customize box colors
colors = ['lightblue', 'lightgreen', 'lightcoral', 'lightyellow']
for patch, color in zip(box_plot['boxes'], colors):
patch.set_facecolor(color)
# Set labels and title
ax.set_xticklabels(data.keys())
ax.set_title('Multiple Boxplots with Custom Colors')
ax.set_ylabel('Values')
ax.grid(True, alpha=0.3)
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
patch_artist |
Fill boxes with color | True/False |
notch |
Add confidence interval notches | True/False |
showmeans |
Display mean markers | True/False |
Conclusion
Creating multiple boxplots from a dictionary is straightforward using boxplot(data.values()) and set_xticklabels(data.keys()). This approach allows easy comparison of distributions across different groups or categories.
Advertisements
