Matplotlib boxplot() Function


Matplotlib 参考文档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

ParameterTypeDescription
xarray or sequence of arraysInput data; a one-dimensional array draws one box, a sequence of two-dimensional arrays draws multiple boxes
notchboolWhether to draw a notched box plot (notches are used for the median confidence interval), default False
vertboolTrue=vertical (default), False=horizontal
whisfloat or (float, float)Whisker length (multiple of IQR), default 1.5. For example, (5, 95) means the 5th and 95th percentiles
symstr or NoneMarker style for outliers; None means outliers are not displayed
widthsfloat or array-likeWidth of each box
patch_artistboolIf True, boxes are filled with a fill color (can be customized with facecolor)
showmeansboolWhether to display mean points, default False
showfliersboolWhether to display outliers, default True
labelslistLabel for each box
boxprops / flierprops / medianprops / meanpropsdictControl 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 matplotlib.pyplot as plt
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 matplotlib.pyplot as plt
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 matplotlib.pyplot as plt
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.


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions