Seaborn Boxplot: Order, Hue, Whiskers, and Outliers in sns.boxplot()

How to make a box plot with sns.boxplot(): what the box and whiskers mean, horizontal boxes, sorting by median, side-by-side groups with hue, whis= and showfliers= for outliers, showing the mean, log scales, and styling.

sns.boxplot(data=df, x="category", y="value") draws one box per category: the line in the middle is the median, the box spans the 25th to 75th percentiles, and the whiskers reach the furthest points within 1.5 times the box height. Points beyond the whiskers are drawn as outliers. Put the numeric column on x for horizontal boxes, sort them with order=, and split each box into groups with hue=. The examples use Seaborn 0.13.2 and Matplotlib 3.11.

Quick Example

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

# Simulated API response times: 150 requests per endpoint and release
rng = np.random.default_rng(83)
rows = []
for endpoint, median_ms, spread in [("/login", 120, 0.30), ("/search", 340, 0.45),
                                    ("/checkout", 520, 0.35), ("/profile", 90, 0.25)]:
    for release, speedup in [("v1", 1.0), ("v2", 0.75 if endpoint == "/search" else 0.95)]:
        ms = rng.lognormal(np.log(median_ms * speedup), spread, 150)
        slow = rng.random(150) < 0.03  # a few slow requests (timeouts, cold caches)
        ms[slow] *= rng.uniform(2.5, 4, slow.sum())
        rows.append(pd.DataFrame({"endpoint": endpoint, "release": release, "ms": ms.round()}))
requests = pd.concat(rows, ignore_index=True)

sns.set_theme(style="ticks")
fig, ax = plt.subplots(figsize=(7, 4.5))
sns.boxplot(data=requests, x="endpoint", y="ms", color="#8fb3d9", ax=ax)
ax.set(title="API response time by endpoint", xlabel="", ylabel="Response time (ms)")
sns.despine()
plt.show()

Seaborn box plot of API response time for four endpoints: /checkout has the highest median at about 520 ms, /search about 305 ms, /login 120 ms and /profile 86 ms, with outlier points above each box up to about 2,000 ms

How do you read a Seaborn box plot?

Each box summarizes one category's values with five numbers, the same ones Matplotlib's boxplot uses:

  • Median: the line inside the box.
  • Box: the first quartile (25th percentile) to the third quartile (75th percentile). Its height is the interquartile range (IQR), which holds the middle half of the data.
  • Whiskers: they extend to the furthest data point that is still within 1.5 * IQR of the box. They stop at a real data point, so they are often shorter on one side.
  • Outliers (fliers): every point past the whiskers, drawn as an open circle.

You can get the same numbers with pandas to check a chart or put them in a table:

stats = requests.groupby("endpoint")["ms"].describe()[["25%", "50%", "75%"]]
stats["IQR"] = stats["75%"] - stats["25%"]
print(stats.round())
             25%    50%    75%    IQR
endpoint
/checkout  423.0  522.0  682.0  259.0
/login      97.0  120.0  148.0   51.0
/profile    74.0   86.0  103.0   29.0
/search    212.0  306.0  408.0  196.0

For /login, the upper whisker can reach 148 + 1.5 * 51 = 224.5 ms, so it stops at the slowest request at or below that (224 ms), and the 13 slower requests are drawn as outliers. All four endpoints have outliers because of the simulated slow requests (8 for /checkout, 13 for /login and /search, 14 for /profile).

Make a horizontal box plot

Put the numeric column on x and the categories on y. Seaborn works out the orientation from the column types, so you don't need orient= unless both columns are numeric. Horizontal boxes leave room for long category names, and order= sets the order from top to bottom. Here the boxes are sorted by median:

by_median = requests.groupby("endpoint")["ms"].median().sort_values(ascending=False).index

fig, ax = plt.subplots(figsize=(7, 4))
sns.boxplot(data=requests, x="ms", y="endpoint", order=by_median, color="#e3a587", ax=ax)
ax.set(title="Endpoints sorted by median response time", xlabel="Response time (ms)", ylabel="")
sns.despine()
plt.show()

Horizontal Seaborn box plot with endpoints sorted by median response time from top to bottom: /checkout, /search, /login, /profile, with outliers trailing to the right

order= takes any list of category names, so you can also use it to drop categories or fix the order across several charts. Ordering categories in Seaborn covers more ways to do this.

Compare groups side by side with hue

hue= splits each box into one box per group, placed next to each other and colored by palette=. gap= (added in Seaborn 0.13) leaves a little space between the boxes in a pair:

fig, ax = plt.subplots(figsize=(7, 4.5))
sns.boxplot(data=requests, x="endpoint", y="ms", hue="release",
            palette={"v1": "#b8b8b8", "v2": "#3b7dd8"}, gap=0.15, ax=ax)
ax.set(title="Response time before and after the v2 release", xlabel="", ylabel="Response time (ms)")
sns.move_legend(ax, "upper left", title="Release", frameon=False)
sns.despine()
plt.show()

Seaborn box plot with hue: gray v1 and blue v2 boxes side by side for each endpoint, the v2 box for /search sits clearly lower than v1 while the other endpoints barely change

The v2 release cut the median /search time from 340 ms to about 276 ms (19% faster), while the other three endpoints moved by 6% or less. To move the legend outside the axes, see moving a Seaborn legend.

Change the whiskers and hide the outliers

whis= controls how far the whiskers reach. A number is a multiple of the IQR (the default is 1.5), and a pair of numbers is a pair of percentiles. whis=(0, 100) stretches the whiskers to the minimum and maximum, so no points are drawn as outliers. To keep the default whiskers and just stop drawing the outlier points, pass showfliers=False. Seaborn passes this through to Matplotlib:

fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
sns.boxplot(data=requests, x="endpoint", y="ms", whis=(0, 100), color="#9fcfb0", ax=axes[0])
axes[0].set(title="whis=(0, 100): whiskers to min and max", xlabel="", ylabel="Response time (ms)")
sns.boxplot(data=requests, x="endpoint", y="ms", showfliers=False, color="#9fcfb0", ax=axes[1])
axes[1].set(title="showfliers=False: outliers hidden", xlabel="")
sns.despine()
plt.show()

Two Seaborn box plots side by side: on the left whis=(0, 100) stretches the whiskers to each endpoint's minimum and maximum, up to about 2,000 ms; on the right showfliers=False keeps the default whiskers and hides the outlier points

showfliers=False doesn't change the y-axis limits by itself here, because sharey=True ties the right panel to the left one. On its own Axes, the hidden outliers let the axis zoom in on the boxes. Hiding outliers is fine for a quick comparison of medians, but say so in the caption: the slow requests are often the part people care about. You can also change the outlier markers' size with fliersize= or their style with flierprops={"marker": "x"}.

Show the mean and use a log scale

Response times are skewed, so the boxes for fast endpoints get squashed at the bottom of a linear axis. log_scale=True (also new in 0.13) computes the boxes on a log scale and gives each endpoint similar room. showmeans=True adds a marker for the mean, and meanprops= styles it:

fig, ax = plt.subplots(figsize=(7, 4.5))
sns.boxplot(data=requests, x="endpoint", y="ms", log_scale=True, showmeans=True,
            meanprops={"marker": "o", "markerfacecolor": "white", "markeredgecolor": "#222222"},
            color="#c9b3e6", ax=ax)
ax.set(title="Log scale, with the mean marked", xlabel="", ylabel="Response time (ms, log scale)")
sns.despine()
plt.show()

Seaborn box plot on a log y-axis with a white dot for the mean on each box; the four endpoints get similar room and the boxes look roughly symmetric

On the log axis the boxes look roughly symmetric, which tells you the response times are close to log-normal. One catch: with log_scale=True, Seaborn computes everything on the log values, so the whiskers are 1.5 IQR in log space (that's why some fast requests now show up as outliers below the boxes), and the showmeans marker is the geometric mean, not the arithmetic mean. For /search the marker sits at 300 ms, while requests.groupby("endpoint")["ms"].mean() gives 341 ms. If you want the arithmetic mean, plot on a linear axis and call ax.set_yscale("log") afterward, which changes only the axis, not the statistics.

Style the boxes: outline only, colors, and line width

fill=False draws only the outlines. With hue, the outlines take the palette's colors. linecolor= sets the color of the median, whiskers, and box edges when the boxes are filled, linewidth= sets their width, and width= sets the box width as a fraction of the space for each category (the default is 0.8):

fig, ax = plt.subplots(figsize=(7, 4.5))
sns.boxplot(data=requests, x="endpoint", y="ms", hue="release", fill=False,
            palette=["#7a7a7a", "#d1495b"], linewidth=1.6, width=0.6, gap=0.2, ax=ax)
ax.set(title="Outline-only boxes with fill=False", xlabel="", ylabel="Response time (ms)")
sns.move_legend(ax, "upper left", title="Release", frameon=False)
sns.despine()
plt.show()

Seaborn box plot with fill=False: gray v1 and red v2 outline-only boxes side by side for each endpoint, with outliers in matching colors

For any other style, pass Matplotlib's property dicts: boxprops=, whiskerprops=, capprops=, medianprops=, and flierprops=. medianprops={"color": "black", "linewidth": 2}, for example, makes the median stand out on light boxes.

Show every point on top of the boxes

A box plot hides the number of points and any gaps or clusters in the data. Drawing the raw points on top fixes both. Use sns.stripplot (jittered points) or sns.swarmplot (non-overlapping points), and pass showfliers=False to the box plot so the outliers aren't drawn twice. The box plot with swarm overlay post shows how to line the points up with hue groups using dodge=True.

Why does sns.boxplot print a vert deprecation warning?

On Matplotlib 3.11 or newer, every sns.boxplot call with Seaborn 0.13.2 prints:

MatplotlibDeprecationWarning: vert: bool was deprecated in Matplotlib 3.11 and will be removed in 3.13. Use orientation: {'vertical', 'horizontal'} instead.

The warning comes from Seaborn's own code, which passes vert= to Matplotlib's bxp(). Your code didn't cause it, the chart is correct, and passing orient= doesn't stop it. Seaborn 0.13.2 is still the latest release, so to hide the warning until a fix ships, filter it:

import warnings

warnings.filterwarnings("ignore", message="vert: bool was deprecated")

sns.boxplot vs violinplot, boxenplot, stripplot, and catplot

Function What it shows Use it when
sns.boxplot Median, quartiles, whiskers, outliers You want to compare medians and spread across many groups
sns.violinplot A density curve for each group The shape matters, for example two peaks (violin plots)
sns.boxenplot More quantiles as nested boxes You have thousands of points per group and care about the tails
sns.stripplot, sns.swarmplot Every point Groups are small (under a few hundred points) (beeswarm plots)
sns.catplot(kind="box") Box plots in a grid of subplots You want one panel per value of another column (col=, row=)

sns.boxplot is an axes-level function: it draws on one Matplotlib Axes and accepts ax=. sns.catplot(kind="box") is the figure-level version, which builds its own figure and returns a FacetGrid. See figure-level vs axes-level functions for the differences. Without Seaborn, use Matplotlib's ax.boxplot or df.boxplot() in pandas.

Practical Tips

  • Pass long-form data. One row per observation, with a column for the category and a column for the value. A wide DataFrame (sns.boxplot(data=df)) also works and draws one box per numeric column.
  • Sort by median with order= when the categories have no natural order. It makes the chart much easier to scan.
  • Check the group sizes. A box built from 8 points looks as solid as one built from 8,000. Add the counts to the tick labels or overlay the points.
  • Use log_scale=True for skewed data such as prices, durations, and incomes, instead of hiding the outliers.

Similar Topics