Outlier Plots in Python: Box Plot, Z-Score and Isolation Forest

Plot outliers in Python: box plot with the 1.5 x IQR rule, log-scale fences, z-score vs modified z-score (MAD), and Isolation Forest for two columns.

To find outliers in a pandas column, compute the quartiles with Series.quantile(), then flag anything outside Q1 - 1.5 * IQR and Q3 + 1.5 * IQR. That is the rule behind every box plot's dots. Plot the flagged points in a different color and you can see what the rule is catching. The sections below compare it with z-scores, a log scale and IsolationForest on the same data. For the box plot itself, see Box Plots in Matplotlib.

This post was run with Matplotlib 3.11, pandas 3.1 and scikit-learn 1.9. orientation="horizontal" in ax.boxplot() needs Matplotlib 3.10 or later (use vert=False on older versions).

Quick Example

The data is 400 simulated orders from an online shop (seeded). Most are ordinary, and three were keyed with an extra digit, so a $48 order shows up as $480.

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

rng = np.random.default_rng(5)
n = 400
items = rng.poisson(3, n) + 1
value = items * rng.lognormal(3.2, 0.3, n)           # order value in dollars
items[:3], value[:3] = [2, 3, 1], [480.0, 610.0, 790.0]  # three orders keyed with an extra digit
orders = pd.DataFrame({"items": items, "value": value.round(2)})

q1, q3 = orders["value"].quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
orders["outlier"] = ~orders["value"].between(low, high)

fig, ax = plt.subplots(figsize=(9, 3.2))
ax.boxplot(orders["value"], orientation="horizontal", widths=0.5, showfliers=False)
jitter = rng.uniform(-0.25, 0.25, n)
ax.scatter(orders["value"], 1 + jitter, c=orders["outlier"].map({False: "#8d99ae", True: "#d62828"}),
           s=14, alpha=0.7)
ax.set(xlabel="Order value ($)", yticks=[], title="Order values with the 1.5 x IQR rule")
plt.show()
print(f"fences: {low:.0f} to {high:.0f}; flagged {orders['outlier'].sum()} of {n}")
fences: -33 to 226; flagged 13 of 400

Horizontal box plot of 400 order values with red dots for the 13 orders above the upper fence of 226 dollars, three of them far out at 480, 610 and 790 dollars

The box spans Q1 ($64) to Q3 ($129) with the median ($93) inside it, and the whiskers stop at the last point inside the fences. The rule flags 13 orders. The jittered dots (random vertical offsets so they don't stack) show how many points sit past the whisker and how far, which a plain box plot only hints at.

Which flagged points are mistakes?

A flag is a question, not a verdict. In this data we know which three orders are wrong (they are the first three rows), so we can check what the rule found:

mistakes = orders.index[:3]
flagged = orders[orders["outlier"]]
print("flagged:", len(flagged), "| typing mistakes caught:", flagged.index.isin(mistakes).sum())
print("median value:", orders["value"].median(), "| lower fence:", round(low))
print(flagged.drop(mistakes).sort_values("value").head(4))
flagged: 13 | typing mistakes caught: 3
median value: 93.385 | lower fence: -33
     items   value  outlier
252      7  230.85     True
267      6  232.40     True
210      6  248.23     True
264      7  248.27     True

All three mistakes are caught, along with ten real orders: nine orders of $231 to $316 with five to ten items, and a ten-item order at $420. Those are not errors. Order values are right-skewed, so a few big baskets always sit far above the typical one, and the rule flags them. The negative lower fence (-$33) shows the same problem from the other side: no order can be below zero, so the lower fence is meaningless on the raw scale.

IQR on a log scale

When values are skewed, apply the rule to np.log10(value) and convert the fences back with 10**fence. The fences become multiplicative, so the lower fence stays positive and the upper fence gets wider:

log_value = np.log10(orders["value"])
lq1, lq3 = log_value.quantile([0.25, 0.75])
liqr = lq3 - lq1
log_low, log_high = lq1 - 1.5 * liqr, lq3 + 1.5 * liqr
orders["outlier_log"] = ~log_value.between(log_low, log_high)
print("flagged on the log scale:", orders["outlier_log"].sum(),
      "| fences: $%.0f to $%.0f" % (10**log_low, 10**log_high))

fig, axes = plt.subplots(1, 2, figsize=(11, 3.8), sharey=True)
axes[0].hist(orders["value"], bins=np.arange(0, 820, 20), color="#8d99ae")
axes[0].axvline(high, color="#d62828", ls="--", label=f"upper fence ${high:.0f}")
axes[0].set(title="Raw dollars", xlabel="Order value ($)", ylabel="Orders")
axes[1].hist(orders["value"], bins=np.logspace(0.8, 3, 40), color="#8d99ae")
axes[1].axvline(10**log_high, color="#d62828", ls="--", label=f"upper fence ${10**log_high:.0f}")
axes[1].axvline(10**log_low, color="#d62828", ls="--", label=f"lower fence ${10**log_low:.0f}")
axes[1].set(xscale="log", title="Log scale", xlabel="Order value ($, log scale)")
for ax in axes:
    ax.legend()
fig.tight_layout()
plt.show()
flagged on the log scale: 9 | fences: $22 to $367

Two histograms of order values, the left in dollars with an upper fence at 226 and a long right tail, the right on a log scale looking roughly bell shaped with fences at 22 and 367 dollars

On the log scale the histogram is close to symmetric, which is what the IQR rule assumes. The fences are now $22 and $367, and 9 orders are flagged. Four are on the high side: the three keying mistakes and the $420 ten-item order. Five are on the low side, one-item orders of $13 to $22. Whether those count as outliers is a business question. They are cheap single items, not errors, and the raw-scale rule could never have flagged them.

Z-score vs modified z-score

The z-score, (x - mean) / std, flags points more than 3 standard deviations from the mean. It has a weakness: outliers inflate the mean and the standard deviation it uses. The three mistakes push the standard deviation to $70.6, against $53.1 without them. The modified z-score replaces the mean with the median and the standard deviation with the median absolute deviation (MAD): 0.6745 * (x - median) / MAD, with 3.5 as the usual cutoff.

v = orders["value"]
z = (v - v.mean()) / v.std()
mad = (v - v.median()).abs().median()
modified_z = 0.6745 * (v - v.median()) / mad

print("z-score > 3:", (z.abs() > 3).sum(), "| modified z > 3.5:", (modified_z.abs() > 3.5).sum())
print("largest z-scores:", z.nlargest(3).round(1).tolist())

rules = {
    "IQR rule (1.5 x IQR)": orders["outlier"],
    "Z-score above 3": z.abs() > 3,
    "Modified z above 3.5": modified_z.abs() > 3.5,
}
fig, ax = plt.subplots(figsize=(9, 3.6))
for row, (name, hit) in enumerate(rules.items()):
    jitter = rng.uniform(-0.2, 0.2, n)
    ax.scatter(v[~hit], row + jitter[~hit], s=10, color="#8d99ae", alpha=0.6)
    ax.scatter(v[hit], row + jitter[hit], s=22, color="#d62828")
ax.set(yticks=range(len(rules)), yticklabels=[f"{k}\n{h.sum()} flagged" for k, h in rules.items()],
       xlabel="Order value ($)", title="The same 400 orders under three rules")
ax.invert_yaxis()
plt.show()
z-score > 3: 4 | modified z > 3.5: 9
largest z-scores: [9.7, 7.2, 5.3]

Three strip plots of the same 400 order values, flagged red under the IQR rule (13 points), the z-score above 3 (4 points) and the modified z-score above 3.5 (9 points)

The z-score flags only the four largest orders ($420, $480, $610 and $790). The orders from $231 to $316 stay inside 3 standard deviations because the big values made the standard deviation larger. This is called masking. The modified z-score flags 9, and the IQR rule 13, because the median, MAD and quartiles hardly move when a few extreme values are added. Use the z-score only when the data is roughly bell-shaped and you do not expect extreme values. Otherwise prefer the IQR rule or the modified z-score.

Outliers in two dimensions with Isolation Forest

A single-column rule can't tell that $790 is odd for a one-item order but ordinary for a ten-item one. IsolationForest from scikit-learn scores each row using several columns at once. It splits the data at random, and points that get isolated in few splits are the outliers. contamination=0.02 tells it to flag about 2% of rows (8 of 400). The default, "auto", picks the cutoff from the model's own scores instead, so set it when you know roughly how many you expect.

from sklearn.ensemble import IsolationForest

model = IsolationForest(contamination=0.02, random_state=0)
orders["iso"] = model.fit_predict(orders[["items", "value"]]) == -1

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.scatter(orders.loc[~orders["iso"], "items"], orders.loc[~orders["iso"], "value"],
           s=18, color="#8d99ae", alpha=0.7, label="inlier")
ax.scatter(orders.loc[orders["iso"], "items"], orders.loc[orders["iso"], "value"],
           s=40, color="#d62828", label="flagged by Isolation Forest")
ax.set(xlabel="Items in order", ylabel="Order value ($)", title="Isolation Forest on items and value")
ax.legend()
plt.show()
print("flagged:", orders["iso"].sum(), "| mistakes among them:", orders.index[orders["iso"]].isin(mistakes).sum())
flagged: 8 | mistakes among them: 3

Scatter plot of order value against items per order, with eight red points flagged by Isolation Forest, including $790 for one item, $610 for three items and $480 for two items, far above the band of normal orders

All three keying mistakes are flagged, and they stand out clearly because a $790 order with one item sits far above the band of normal values. The other five are the orders that sit highest for a given item count: $274, $310, $316 and $420 for 6 to 10 items, plus an eight-item order at $118 on the low edge of its group. Isolation Forest is random, so set random_state to get the same flags on every run, and check the flagged rows before you drop anything.

Which outlier method should I use?

Method Looks at Strength Weakness
1.5 x IQR rule (box plot) One column Robust, matches the box plot Flags the long tail of skewed data
IQR on log10(x) One column Handles skewed, positive data Flags unusually small values too
Z-score above 3 One column Simple, widely known Extreme values mask each other
Modified z-score (MAD) One column Robust to extreme values Cutoff of 3.5 is a convention
IsolationForest Several columns Finds unusual combinations Random, needs contamination

Practical Tips

  • Plot before you remove. A box plot with the points on top shows whether you have three typing mistakes or a long tail of valid values.
  • Check the lower fence. If it comes out negative for data that can't be negative, the data is skewed and a log scale will fit better.
  • Do not delete flagged rows automatically. The rules find unusual values, not wrong ones. Fix confirmed mistakes, and keep (or cap) the real ones.
  • ax.boxplot(showfliers=False) hides the box plot's own dots. This post draws the points itself so they can be colored by whichever rule you chose. The fence multiplier is the whis argument, which defaults to 1.5.
  • Use Series.between() for the filter. df[df["value"].between(low, high)] keeps the non-outliers, and ~ in front of it keeps the outliers.

Similar Topics