Box plot
- Machine Learning course
- Beginner
- Lesson 107/112
- 5 min
A box plot shows data spread and outliers.
Box plot
A box plot summarises a distribution with five numbers: the box is the first and third quartile (Q1, Q3), the middle line the median, the whiskers reach up to the 1.5·IQR limit; points outside are outliers.
fig, ax = plt.subplots()
ax.boxplot([X[y == 0, 0], X[y == 1, 0], X[y == 2, 0]])
ax.set_xticks([1, 2, 3], ["setosa", "versicolor", "virginica"])It is tidier than a histogram for comparing several groups side by side.
Computing outliers
The outliers the plot marks can be found by hand with the same rule. This decides which examples to examine in the cleaning step:
q1, q3 = np.percentile(x, [25, 75])
iqr = q3 - q1
aykiri = x[(x < q1 - 1.5 * iqr) | (x > q3 + 1.5 * iqr)]The plot and the calculation should agree; if they don't, the percentile method usually differs.
Practice Box and outliers
Draw a box plot of x and save it. Print the median, then the outliers by the 1.5·IQR rule, on separate lines.
Starter code
import numpy as np
import matplotlib.pyplot as plt
x = np.array([12, 14, 15, 15, 16, 17, 18, 19, 40])
# buraya yazSample solution
import numpy as np
import matplotlib.pyplot as plt
x = np.array([12, 14, 15, 15, 16, 17, 18, 19, 40])
fig, ax = plt.subplots()
ax.boxplot(x)
fig.savefig("kutu.png")
print(np.median(x))
q1, q3 = np.percentile(x, [25, 75])
iqr = q3 - q1
print(x[(x < q1 - 1.5 * iqr) | (x > q3 + 1.5 * iqr)])Expected output
16.0 [40]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the line in the middle of the box show in a box plot?
- The median Correct answer
- The mean
- The mode
- The standard deviation
Explanation: A box plot is based on quartiles; the middle line is the 50th percentile.
2 Draw the groups as a box plot.
ax.____([a, b, c])
ax.boxplot([a, b, c])
Explanation: boxplot takes a list of arrays; each becomes a separate box.
3 Match the box plot parts.
| Term | Meaning |
|---|---|
box |
Between Q1 and Q3 |
middle line |
Median |
whisker |
1.5·IQR limit |
outlier point |
Outlier |