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 create a Boxplot with Matplotlib?
A boxplot (also called a box-and-whisker plot) is a statistical visualization that displays the distribution of data through quartiles. Matplotlib provides simple methods to create boxplots for data analysis.
Basic Boxplot with Single Dataset
Let's start with a simple example using matplotlib's built-in boxplot function ?
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20]
# Create figure and plot boxplot
plt.figure(figsize=(8, 6))
plt.boxplot(data)
plt.title('Simple Boxplot')
plt.ylabel('Values')
plt.show()
Multiple Boxplots with Custom Labels
Here's how to create multiple boxplots with custom labels and styling ?
import matplotlib.pyplot as plt
import numpy as np
# Create multiple datasets
dataset1 = [1, 4, 5, 2, 3, 8, 6, 7]
dataset2 = [2, 6, 8, 3, 5, 9, 7, 4]
dataset3 = [3, 7, 9, 4, 6, 10, 8, 5]
# Combine data
data_to_plot = [dataset1, dataset2, dataset3]
# Create the boxplot
plt.figure(figsize=(10, 6))
box = plt.boxplot(data_to_plot, patch_artist=True)
# Customize colors
colors = ['lightblue', 'lightgreen', 'pink']
for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)
# Add labels and title
plt.xticks([1, 2, 3], ['Dataset A', 'Dataset B', 'Dataset C'])
plt.ylabel('Values')
plt.title('Multiple Boxplots with Custom Styling')
plt.grid(True, alpha=0.3)
plt.show()
Using Seaborn for Enhanced Boxplots
Seaborn provides more advanced boxplot functionality with better default styling ?
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Create sample data
np.random.seed(42)
data = pd.DataFrame({
'Category': ['A'] * 50 + ['B'] * 50 + ['C'] * 50,
'Values': np.concatenate([
np.random.normal(10, 2, 50),
np.random.normal(15, 3, 50),
np.random.normal(12, 1.5, 50)
])
})
# Create boxplot with seaborn
plt.figure(figsize=(10, 6))
sns.boxplot(data=data, x='Category', y='Values', palette='Set2')
plt.title('Boxplot using Seaborn')
plt.ylabel('Values')
plt.show()
Boxplot Components
Key Parameters
| Parameter | Description | Example |
|---|---|---|
patch_artist |
Enable color filling | patch_artist=True |
notch |
Add notches around median | notch=True |
vert |
Vertical orientation | vert=False |
widths |
Box width | widths=0.6 |
Conclusion
Boxplots are essential for visualizing data distribution and identifying outliers. Use matplotlib for basic plots or seaborn for enhanced styling and statistical features.
Advertisements
