Matplotlib boxplot() Function
Matplotlib Reference Documentation
boxplot()Used to draw box plots, intuitively displaying the five-number summary of data: minimum, first quartile, median, third quartile, maximum, and possible outliers.
Box plots are a core tool for exploratory data analysis, suitable for comparing the distribution characteristics of multiple groups of data.
Function Definition
matplotlib.pyplot.boxplot(x, notch=None, sym=None, vert=None,
whis=None, positions=None, widths=None, patch_artist=None,
bootstrap=None, usermedians=None, conf_intervals=None,
meanline=None, showmeans=None, showcaps=None, showbox=None,
showfliers=None, boxprops=None, labels=None, flierprops=None,
medianprops=None, meanprops=None, capprops=None,
whiskerprops=None, manage_ticks=True, autorange=False,
zorder=None, capwidths=None, **kwargs)
Parameter Description
| Parameter | Type | Description |
|---|---|---|
| x | array or sequence of arrays | Input data; a one-dimensional array draws one box, a sequence of two-dimensional arrays draws multiple boxes |
| notch | bool | Whether to draw a notched box plot (notches are used for the median confidence interval), default False |
| vert | bool | True=vertical (default), False=horizontal |
| whis | float or (float, float) | Whisker length (multiple of IQR), default 1.5. For example, (5, 95) means the 5th and 95th percentiles |
| sym | str or None | Marker style for outliers; None means outliers are not displayed |
| widths | float or array-like | Width of each box |
| patch_artist | bool | If True, boxes are filled with a fill color (can be customized with facecolor) |
| showmeans | bool | Whether to display mean points, default False |
| showfliers | bool | Whether to display outliers, default True |
| labels | list | Label for each box |
| boxprops / flierprops / medianprops / meanprops | dict | Control the appearance properties of boxes/outliers/median lines/means respectively |
Structure of a box plot: the box spans from Q1 to Q3, and the middle line is the median. The whiskers extend to the farthest data points within the range of Q1-1.5*IQR to Q3+1.5*IQR. Values beyond the whiskers are outliers.
Usage Examples
Example 1: Basic Box Plot
Example
import numpy as np
np.random.seed(42)
# Three groups of data with different distributions
data = [
np.random.normal(0, 1, 100), # Standard normal
np.random.normal(2, 1.5, 100), # mean=2, standard deviation=1.5
np.random.normal(-1, 0.5, 100), # mean=-1, standard deviation=0.5
]
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
bp = ax.boxplot(data, labels=['Group A', 'Group B', 'Group C'],
patch_artist=True)
# Custom colors
colors = ['#3498db', '#e74c3c', '#2E7DCC']
for patch, color in zip(bp['boxes'], colors):
patch.set_facecolor(color)
ax.set_title('Box Plot: Comparing Three Groups')
ax.set_ylabel('Value')
ax.grid(axis='y', alpha=0.3)
plt.show()
Example 2: Notched Box Plot + Show Mean
Example
import numpy as np
np.random.seed(42)
data = [
np.random.normal(0, 1, 100),
np.random.normal(0, 1.2, 100),
np.random.normal(0.3, 1, 100),
]
fig, ax = plt.subplots(figsize=(7, 5), layout='constrained')
bp = ax.boxplot(data,
notch=True, # Notch (median confidence interval)
showmeans=True, # Show mean
meanprops=dict(marker='D', markerfacecolor='red',
markersize=8),
patch_artist=True,
labels=['Control', 'Test A', 'Test B'])
colors = ['#bdc3c7', '#3498db', '#2E7DCC']
for patch, color in zip(bp['boxes'], colors):
patch.set_facecolor(color)
ax.set_title('Notched Box Plot with Means')
ax.set_ylabel('Measurement')
ax.grid(axis='y', alpha=0.3)
plt.show()
Example 3: Horizontal Box Plot
Example
import numpy as np
np.random.seed(42)
data = [np.random.exponential(scale=s, size=100) for s in [1, 2, 3, 4]]
labels = ['Scale=1', 'Scale=2', 'Scale=3', 'Scale=4']
fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
bp = ax.boxplot(data, labels=labels,
vert=False, # Horizontal direction
patch_artist=True)
colors = ['#e74c3c', '#f39c12', '#2E7DCC', '#3498db']
for patch, color in zip(bp['boxes'], colors):
patch.set_facecolor(color)
patch.set_alpha(0.7)
ax.set_title('Horizontal Box Plot')
ax.set_xlabel('Value')
ax.grid(axis='x', alpha=0.3)
plt.show()
FAQ
What do the parts of a box plot mean?
Box: The IQR (interquartile range) from Q1 (25%) to Q3 (75%).
Median line: The line in the middle of the box = Q2 (50%).
Whiskers: Extend to the farthest data points within Q1-1.5*IQR and Q3+1.5*IQR.
Outliers: Individual data points outside the whisker range.
Other Extensions