Skip to content

Matplotlib - Box Plot

A box plot (or box-and-whisker plot) provides a concise visual summary of a dataset’s distribution. It displays key statistical measures:

  • Median: The central line inside the box (50th percentile).
  • Interquartile Range (IQR): The box itself represents the range between the first quartile (Q1, 25th percentile) and the third quartile (Q3, 75th percentile). The length of the box indicates the spread of the central 50% of the data.
  • Whiskers: Lines extending from the box, typically reaching 1.5 times the IQR from the box edges, or to the minimum/maximum data points if they fall within this range.
  • Outliers: Individual points plotted beyond the whiskers, representing potential extreme values.

Box plots are particularly useful for comparing the distributions of different datasets side-by-side.

We’ll use NumPy’s random number generator to create sample data, simulating measurements from different groups.

import numpy as np
# Use the recommended modern way to generate random numbers
rng = np.random.default_rng(seed=42) # Seed for reproducibility
# Create four datasets with different distributions
data_group1 = rng.normal(loc=100, scale=10, size=200) # Mean 100, Std Dev 10
data_group2 = rng.normal(loc=80, scale=30, size=200) # Mean 80, Std Dev 30
data_group3 = rng.normal(loc=90, scale=20, size=200) # Mean 90, Std Dev 20
data_group4 = rng.normal(loc=70, scale=25, size=200) # Mean 70, Std Dev 25
# Combine the datasets into a list for plotting
data_to_plot = [data_group1, data_group2, data_group3, data_group4]

The ax.boxplot() method (using the object-oriented API) is used to create the plot. The primary input is a list of datasets or a 2D array where columns represent datasets.

import matplotlib.pyplot as plt
import numpy as np
# (Include data generation code from above)
rng = np.random.default_rng(seed=42)
data_group1 = rng.normal(loc=100, scale=10, size=200)
data_group2 = rng.normal(loc=80, scale=30, size=200)
data_group3 = rng.normal(loc=90, scale=20, size=200)
data_group4 = rng.normal(loc=70, scale=25, size=200)
data_to_plot = [data_group1, data_group2, data_group3, data_group4]
# --- Create Plot ---
fig, ax = plt.subplots(figsize=(8, 6))
# Create the boxplot
# 'patch_artist=True' fills the boxes with color
# 'showmeans=True' displays the mean as a marker
bp = ax.boxplot(data_to_plot, patch_artist=True, showmeans=True,
boxprops=dict(facecolor='lightblue'),
medianprops=dict(color='red', linewidth=2),
meanprops=dict(marker='D', markeredgecolor='black', markerfacecolor='green'))
# --- Customize Plot ---
ax.set_title('Comparison of Data Distributions')
ax.set_ylabel('Measurement Value')
ax.set_xlabel('Data Group')
# Set custom labels for the x-axis ticks
ax.set_xticklabels(['Group 1', 'Group 2', 'Group 3', 'Group 4'])
ax.yaxis.grid(True, linestyle='--', which='major', color='grey', alpha=0.5)
plt.show()

This code will generate a figure with four box plots, one for each data group. The boxes will be light blue, medians red, and means marked with green diamonds. Custom labels are provided for the x-axis, and a horizontal grid aids comparison. This visualization clearly shows differences in median values, spread (IQR), and the presence of outliers across the groups.

  • x: The input data (list of arrays or 2D array).
  • vert: Set to False for horizontal box plots.
  • patch_artist: If True, draws boxes using Patch artists, allowing fill colors.
  • labels: A list of strings for labeling each box plot on the x-axis.
  • showmeans: If True, displays the arithmetic mean.
  • showfliers: If False, hides the outlier points.
  • meanprops, medianprops, boxprops, whiskerprops, capprops, flierprops: Dictionaries to customize the appearance of different plot elements.