Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathExplore a Dataset Before You Model
  1. 1
    First Look at a Dataset: 6 Checks Before You Plot or Model
  2. 2
    Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  3. 3
    Scatter Plots and Pair Plots: See How Two Columns Relate
  4. 4
    Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  5. 5
    Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  6. 6
    Train-Test Split and Data Leakage: Split First, Learn After
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Exploratory Data Analysis

Learning path: Explore a Dataset Before You Model · Step 4 of 6

Finding Outliers: Box Plots, Violin Plots and the IQR Rule

Read a box plot from its five numbers, flag outliers with the 1.5 x IQR rule in pandas, compare groups with box and violin plots, and cap extreme values with clip. Shown on 244 restaurant bills.

Chaand Sheikh

·27 November 2026Exploratory Data Analysis

What you will learn

  • Read a box plot: the box, the median, the whiskers and the outlier dots
  • Apply the IQR rule in pandas to find the fences and flag outliers
  • Compare groups with box plots and violin plots
  • Decide whether to drop, keep or cap an outlier, and cap values with clip

Before you start

  • Reading a CSV with pandas
  • Plotting Distributions with seaborn

Think of the queue at airport security. Bags come along the belt one after the other, and most go straight through. A few get pulled aside for a second look.

In your data, a bag is one value, and the ones pulled aside are the outliers: values that sit far from all the others. A box plot shows them at a glance. In this lesson you'll read a box plot, flag outliers with one simple rule, and decide what to do with them, using the 244 restaurant bills from the tips dataset.

The five numbers behind a box plot

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

tips = pd.read_csv("tips.csv")
iris = pd.read_csv("iris.csv")

tips["total_bill"].describe()
count    244.000000
mean      19.785943
std        8.902412
min        3.070000
25%       13.347500
50%       17.795000
75%       24.127500
max       50.810000
Name: total_bill, dtype: float64

The 25% row is the first quartile (Q1), 50% is the median, and 75% is the third quartile (Q3). A box plot is built from these.

What a box plot draws

sns.boxplot(data=tips, x="total_bill")
plt.show()
Box plot of total_bill mapped to quartiles and fences Q1 13.35 median 17.80 Q3 24.13 upper fence 40.30 min 3.07 9 outliers IQR 10.78 1.5 x IQR 0 10 20 30 40 50 total_bill ($)
The box is the middle half of the bills (Q1 to Q3). The whiskers reach the last bill that is still inside the fences. Anything beyond a fence is drawn as a dot (seaborn draws them on one line; here close dots are nudged apart so all nine show). The lower fence is -2.82, below zero, so the left whisker simply reaches the smallest bill.

Reading it piece by piece:

  • The box covers the middle half of the bills, from Q1 (13.35) to Q3 (24.13).
  • The line inside is the median, about 17.80 dollars.
  • The whiskers reach out to the last bill that isn't too far from the box. They stop at a real bill, not at the fence itself.
  • The dots beyond the whiskers are the outliers.

How does seaborn decide what "too far" means? It uses a rule, and you can write it yourself.

The IQR rule

The IQR (interquartile range) is Q3 minus Q1, the width of the box. The fences sit 1.5 IQRs below Q1 and 1.5 IQRs above Q3. Anything beyond a fence is an outlier.

q1 = tips["total_bill"].quantile(0.25)
q3 = tips["total_bill"].quantile(0.75)
iqr = q3 - q1
lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(round(q1, 2), round(q3, 2), round(iqr, 2))
print(round(lower, 2), round(upper, 2))
13.35 24.13 10.78
-2.82 40.3

The box is 10.78 dollars wide. The upper fence lands at 40.30. The lower fence is -2.82, below zero, so no bill can be under it. Nobody gets paid to eat.

Flag the outliers with a filter

below and above are True/False columns. The bar | means "or", so the filter keeps rows where either one is True.

below = tips["total_bill"] < lower
above = tips["total_bill"] > upper
outliers = tips[below | above]
print(len(outliers))
print(outliers["total_bill"].sort_values().tolist())
9
[40.55, 41.19, 43.11, 44.3, 45.35, 48.17, 48.27, 48.33, 50.81]

Nine bills, from 40.55 up to 50.81. All big bills, none on the low side. These are the nine dots on the right of the box plot.

One box plot per group

Box plots are very useful for comparing groups. Here is the petal length of the three iris species:

sns.boxplot(data=iris, x="species", y="petal_length")
plt.show()
iris.groupby("species").petal_length.median()
species
setosa        1.50
versicolor    4.35
virginica     5.55
Name: petal_length, dtype: float64

The setosa box sits far below the other two, and the boxes don't even touch. Versicolor and virginica overlap only a little. The medians tell the same story: 1.50, 4.35 and 5.55.

A violin plot adds the shape

A box plot has one weakness: it hides the shape. A violin plot shows it.

sns.violinplot(data=iris, x="species", y="petal_length")
plt.show()

The width of each violin shows where values are dense: wide means many, thin means few. It's a smooth curve, mirrored on both sides. Inside, a small box still marks the median and the quartiles.

Use a violin when the shape matters. A group with two peaks would show two bulges, and a plain box plot would hide them.

Drop, keep or cap?

You found an outlier. First ask why it's there. The reason decides the action.

Why it's thereWhat to doExample
An errorFix it or drop itA typing slip: 508.1 instead of 50.81
A real valueUsually keep itA genuinely big dinner bill
Real, but it would bully a sensitive modelCap it at the fencePull 50.81 back to 40.30

Cap the values with clip

capped = tips["total_bill"].clip(lower, upper)
print(tips["total_bill"].max(), round(capped.max(), 2))
50.81 40.3

clip limits every value to between the two fences. Bills inside the fences stay exactly the same; only the nine big ones move to the fence. The largest bill, 50.81, becomes 40.30.

Work out the fences on the training data only. Q1, Q3 and the fences are learned from the data, so they must not see the test rows. See Train-Test Split and Data Leakage.

Common mistakes

  • Dropping every dot automatically. A dot on a box plot is a question, not a verdict. Big dinner bills are real.
  • Thinking the whisker ends at the fence. It ends at the last real value inside the fence.
  • Trusting a box plot for shape. Two peaks vanish inside a box. Use a violin or a histogram (see Plotting Distributions with seaborn).
  • Computing fences on all the data before the split.

Quick recap

StepCodeRestaurant bills
Five numbersdescribe()Q1 13.35, median 17.80, Q3 24.13
See itsns.boxplotDots on the right only
IQR and fencesq3 - q1, 1.5 * iqrIQR 10.78, fences -2.82 and 40.30
Flag themtips[below | above]9 bills, 40.55 to 50.81
See the shapesns.violinplotWidth shows density
Cap themclip(lower, upper)Max 50.81 becomes 40.30

Try it yourself

Use the IQR rule on the tip column. How many outliers are there, and are any on the low side?

The notebook and both datasets are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Scatter Plots and Pair Plots: See How Two Columns Relate
Next →
Correlation and Heatmaps: Covariance, df.corr() and What They Miss
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
First Look at a Dataset: 6 Checks Before You Plot or Model

Six quick pandas checks that tell you what's inside a dataset: size, types, gaps, spread, label balance and duplicates. Shown on 142,193 days of Australian weather.

Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p

Look at one column at a time: read the peak and the tail of a histogram, compare groups with hue, count categories, and tame a long tail with log1p. Shown on restaurant bills and iris flowers.

Scatter Plots and Pair Plots: See How Two Columns Relate

Draw one dot per row with seaborn scatterplot, colour the dots by group with hue, turn a clean split into a one-line rule, and read every pair at once with pairplot. Shown on iris and tips.

Correlation and Heatmaps: Covariance, df.corr() and What They Miss

Put one number on "these two columns move together": why covariance depends on units, how correlation fixes it, scanning every pair with df.corr() and a seaborn heatmap, and the two traps correlation can't see.

On this page
  • The five numbers behind a box plot
  • What a box plot draws
  • The IQR rule
  • Flag the outliers with a filter
  • One box plot per group
  • A violin plot adds the shape
  • Drop, keep or cap?
  • Cap the values with clip
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.