Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Box and Whisker Plots in Matplotlib

Learn how to create box and whisker plots using Matplotlib. Understand quartiles, median, whiskers, interquartile range, outliers and different box plot customization options.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand what a box and whisker plot is.
  • Understand minimum, maximum, median and quartiles.
  • Calculate and understand the interquartile range.
  • Create box plots using Matplotlib.
  • Compare multiple datasets using box plots.
  • Identify outliers in a dataset.
  • Customize box plot colours, lines and markers.
  • Create horizontal and notched box plots.
  • Display mean values and customize whiskers.

2. Introduction to Box and Whisker Plots

A box and whisker plot, also called a box plot, is a statistical chart used to display the distribution of numerical data. It summarizes a dataset using five important statistical values.

These values are minimum, first quartile, median, third quartile and maximum. A box plot also helps identify possible outliers in a dataset.

Real-Life Example

Suppose a teacher wants to compare the marks of students from two different classes. A box plot can show the distribution of marks, the middle value, the spread of marks and any unusually high or low values.

Lower Whisker Q1 Median Q3 Upper Whisker Outlier Box and Whisker Plot Structure

Conceptual diagram showing the box, median, whiskers and a possible outlier.

3. Understanding the Five-Number Summary

A box plot is commonly based on five important statistical values. These values describe the centre and spread of a dataset.

Value Meaning
Minimum The smallest value in the dataset.
First Quartile (Q1) 25% of the data is at or below this value.
Median (Q2) The middle value of the dataset.
Third Quartile (Q3) 75% of the data is at or below this value.
Maximum The largest value in the dataset.

Example Dataset

Consider the following sorted student marks:

10, 20, 30, 40, 50, 60, 70, 80, 90

The five-number summary is:

Minimum = 10
Q1      = 25
Median  = 50
Q3      = 75
Maximum = 90

The exact quartile values can depend on the quartile calculation method. Matplotlib uses its statistical box plot calculations to determine these positions.

4. Understanding Interquartile Range (IQR)

The interquartile range (IQR) measures the spread of the middle 50% of a dataset. It is calculated by subtracting the first quartile from the third quartile.

IQR = Q3 - Q1

Example

Q1 = 25
Q3 = 75

IQR = Q3 - Q1

IQR = 75 - 25

IQR = 50

The IQR is used to identify possible outliers. A common method defines the lower and upper fences as follows:

Lower Fence = Q1 - 1.5 * IQR

Upper Fence = Q3 + 1.5 * IQR

Outlier Calculation

Q1 = 25
Q3 = 75
IQR = 50

Lower Fence = 25 - (1.5 * 50)
            = -50

Upper Fence = 75 + (1.5 * 50)
            = 150

Values below -50 or above 150 are considered possible outliers under this rule.

Remember: IQR represents the distance between Q1 and Q3. It focuses on the middle half of the dataset.

5. Import Matplotlib

Before creating a box plot, import Matplotlib's pyplot module. We will also use NumPy to create sample numerical data.

import matplotlib.pyplot as plt
import numpy as np

The plt.boxplot() function creates a box and whisker plot from one or more datasets.

6. Creating a Basic Box Plot

The simplest way to create a box plot is to pass a list of numerical values to plt.boxplot().

Example

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75, 80, 85]

plt.boxplot(marks)

plt.title("Student Marks Distribution")
plt.ylabel("Marks")

plt.show()

Expected Output

Student Marks Distribution

A box and whisker plot is displayed.

The chart shows:
- The lower whisker
- The first quartile
- The median
- The third quartile
- The upper whisker
Tip: The box represents the middle 50% of the data, while the line inside the box represents the median.

7. Creating Multiple Box Plots

Matplotlib allows you to compare multiple datasets in one chart. Pass a list containing multiple datasets to plt.boxplot().

import matplotlib.pyplot as plt

class_a = [45, 50, 55, 60, 65, 70, 75]
class_b = [50, 55, 60, 65, 70, 75, 80]
class_c = [40, 45, 50, 55, 60, 65, 70]

data = [class_a, class_b, class_c]

plt.boxplot(data)

plt.title("Comparison of Student Marks")
plt.xlabel("Classes")
plt.ylabel("Marks")

plt.xticks(
    [1, 2, 3],
    ["Class A", "Class B", "Class C"]
)

plt.show()

Expected Output

Comparison of Student Marks

Three box plots are displayed:

Box Plot 1 = Class A
Box Plot 2 = Class B
Box Plot 3 = Class C

Each box plot represents the distribution
of marks for its respective class.

Why use multiple box plots?

Multiple box plots help compare the median, spread, variation and possible outliers across different groups or categories.

8. Adding Labels to Box Plots

Use the tick_labels parameter to display category names below the box plots in recent Matplotlib versions.

import matplotlib.pyplot as plt

class_a = [45, 50, 55, 60, 65, 70, 75]
class_b = [50, 55, 60, 65, 70, 75, 80]

data = [class_a, class_b]

plt.boxplot(
    data,
    tick_labels=["Class A", "Class B"]
)

plt.title("Class Marks Comparison")
plt.ylabel("Marks")

plt.show()

Expected Output

Class Marks Comparison

Two box plots are displayed.

The horizontal category labels are:
Class A
Class B
Version Note: Recent Matplotlib versions use tick_labels. Older versions may use the labels parameter instead.

9. Creating Horizontal Box Plots

By default, box plots are vertical. You can create a horizontal box plot by setting vert=False in supported Matplotlib versions.

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75, 80, 85]

plt.boxplot(
    marks,
    vert=False
)

plt.title("Horizontal Box Plot")
plt.xlabel("Marks")

plt.show()

Expected Output

Horizontal Box Plot

A horizontal box and whisker plot is displayed.

The box and whiskers extend from left to right.
The marks are represented on the X-axis.
Tip: In newer Matplotlib versions, orientation="horizontal" is the preferred alternative to vert=False.

Horizontal Box Plot Using orientation

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75, 80, 85]

plt.boxplot(
    marks,
    orientation="horizontal"
)

plt.title("Horizontal Box Plot")
plt.xlabel("Marks")

plt.show()

Expected Output

A horizontal box plot is displayed.
The numerical values are shown along the X-axis.

10. Creating Notched Box Plots

A notched box plot displays a notch around the median. The notch provides an approximate visual indication of uncertainty around the median.

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75, 80, 85]

plt.boxplot(
    marks,
    notch=True
)

plt.title("Notched Box Plot")
plt.ylabel("Marks")

plt.show()

Expected Output

Notched Box Plot

A box plot is displayed with a notch around
the median line.

The notch provides an approximate indication
of uncertainty around the median.
Important: The notch is not a direct representation of the full data range. It is related to an approximate confidence interval for the median.

11. Displaying Mean Values with showmeans

The showmeans parameter displays the arithmetic mean of the dataset on the box plot.

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75, 80, 85]

plt.boxplot(
    marks,
    showmeans=True
)

plt.title("Box Plot with Mean")
plt.ylabel("Marks")

plt.show()

Expected Output

Box Plot with Mean

A box plot is displayed with:
- Median line inside the box
- Mean marker
- Lower and upper whiskers
- Quartile boundaries
Remember: The median and mean are different statistical measurements. A box plot can display both.

12. Identifying Outliers in Box Plots

An outlier is a value that is unusually far from the other observations in a dataset. Matplotlib displays possible outliers as individual points outside the whiskers.

import matplotlib.pyplot as plt

marks = [
    45, 50, 52, 55, 58, 60, 62,
    65, 68, 70, 72, 75, 150
]

plt.boxplot(
    marks,
    showfliers=True
)

plt.title("Box Plot with Outlier")
ylabel = plt.ylabel("Marks")

plt.show()

Expected Output

Box Plot with Outlier

The main box plot displays the normal data distribution.
The value 150 may appear as an individual point
outside the upper whisker.

Important Outlier Parameters

Parameter Description
showfliers=True Displays possible outlier points.
showfliers=False Hides individual outlier markers.
flierprops Customizes the appearance of outlier markers.

13. Customizing Box Plot Colours

Set patch_artist=True to fill the box with colours. You can then customize the box using the returned box plot components.

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75, 80, 85]

fig, ax = plt.subplots()

box = ax.boxplot(
    marks,
    patch_artist=True
)

for patch in box["boxes"]:
    patch.set_facecolor("#93c5fd")
    patch.set_edgecolor("#1d4ed8")

ax.set_title("Colored Box Plot")
ax.set_ylabel("Marks")

plt.show()

Expected Output

Colored Box Plot

The box area is filled with a light blue colour.
The box border is displayed in dark blue.
The median and whiskers remain visible.
Tip: The returned dictionary contains different graphical components such as boxes, medians, whiskers, caps and fliers.

14. Customizing Whiskers and Median Lines

Matplotlib allows you to customize different components of a box plot using properties such as boxprops, medianprops, whiskerprops and capprops.

import matplotlib.pyplot as plt

marks = [45, 50, 55, 60, 65, 70, 75, 80, 85]

plt.boxplot(
    marks,
    patch_artist=True,
    boxprops={
        "facecolor": "#bfdbfe",
        "edgecolor": "#1d4ed8",
        "linewidth": 2
    },
    medianprops={
        "color": "#dc2626",
        "linewidth": 3
    },
    whiskerprops={
        "color": "#16a34a",
        "linewidth": 2
    },
    capprops={
        "color": "#7c3aed",
        "linewidth": 2
    }
)

plt.title("Customized Box Plot")

plt.ylabel("Marks")

plt.show()

Expected Output

Customized Box Plot

Box Fill       : Light Blue
Box Border     : Dark Blue
Median Line    : Red
Whiskers       : Green
Whisker Caps   : Purple
Property Purpose
boxprops Customizes box appearance.
medianprops Customizes the median line.
whiskerprops Customizes whisker lines.
capprops Customizes whisker end caps.
flierprops Customizes outlier markers.
meanprops Customizes the mean marker.

15. Customizing Whisker Range with whis

The whis parameter controls how whiskers are calculated. By default, Matplotlib uses 1.5 times the interquartile range to determine the whisker limits.

import matplotlib.pyplot as plt

marks = [
    40, 45, 48, 50, 52, 55, 58,
    60, 62, 65, 68, 70, 75, 100
]

plt.boxplot(
    marks,
    whis=1.5
)

plt.title("Box Plot with Default Whiskers")

plt.ylabel("Marks")

plt.show()

Expected Output

Box Plot with Default Whiskers

Whiskers extend to the most extreme data points
within the default 1.5 IQR limits.

Values outside the whisker limits may appear
as individual outlier points.

Using a Different Whisker Range

import matplotlib.pyplot as plt

marks = [
    40, 45, 48, 50, 52, 55, 58,
    60, 62, 65, 68, 70, 75, 100
]

plt.boxplot(
    marks,
    whis=2
)

plt.title("Box Plot with Whis = 2")

plt.ylabel("Marks")

plt.show()

Expected Output

Box Plot with Whis = 2

The whisker calculation uses 2 times the IQR.
The whiskers may extend farther than the default
1.5 IQR setting.
Important: Whiskers end at the most extreme observed data points within the calculated limits. They do not necessarily end at the theoretical fence values.

16. Styling Multiple Box Plots

You can create multiple box plots and assign different colours to each box. This makes comparison between categories easier.

import matplotlib.pyplot as plt

class_a = [45, 50, 55, 60, 65, 70, 75]
class_b = [50, 55, 60, 65, 70, 75, 80]
class_c = [40, 45, 50, 55, 60, 65, 70]

data = [class_a, class_b, class_c]

fig, ax = plt.subplots(figsize=(8, 5))

result = ax.boxplot(
    data,
    tick_labels=["Class A", "Class B", "Class C"],
    patch_artist=True,
    showmeans=True
)

colors = ["#93c5fd", "#86efac", "#fcd34d"]

for patch, color in zip(result["boxes"], colors):
    patch.set_facecolor(color)

ax.set_title("Class Performance Comparison")
ax.set_ylabel("Marks")

plt.show()

Expected Output

Class Performance Comparison

Class A = Light Blue Box
Class B = Light Green Box
Class C = Light Yellow Box

Each box plot displays its median and mean marker.

17. Box Plots Using the Object-Oriented API

The object-oriented approach provides better control over the figure and axes. Instead of using plt.boxplot(), use ax.boxplot().

import matplotlib.pyplot as plt

class_a = [45, 50, 55, 60, 65, 70, 75]
class_b = [50, 55, 60, 65, 70, 75, 80]

data = [class_a, class_b]

fig, ax = plt.subplots(figsize=(8, 5))

ax.boxplot(
    data,
    tick_labels=["Class A", "Class B"],
    showmeans=True,
    patch_artist=True
)

ax.set_title("Student Performance")
ax.set_xlabel("Classes")
ax.set_ylabel("Marks")

plt.show()

Expected Output

Student Performance

Two box plots are displayed.
Class A and Class B are compared.
Mean markers are visible on both box plots.

Why use the Object-Oriented API?

It is useful when creating multiple charts, managing different axes and customizing individual plots inside a Matplotlib figure.

18. Important Parameters of plt.boxplot()

Parameter Description Example
x Input numerical data. plt.boxplot(data)
notch Displays a notch around the median. notch=True
vert Controls vertical or horizontal orientation in older versions. vert=False
orientation Controls plot orientation in newer versions. orientation="horizontal"
showmeans Displays the mean value. showmeans=True
showfliers Displays possible outliers. showfliers=True
whis Controls the whisker calculation range. whis=1.5
patch_artist Allows boxes to be filled with colours. patch_artist=True
tick_labels Sets category names. tick_labels=names
boxprops Customizes box appearance. boxprops=props
medianprops Customizes median line appearance. medianprops=props
flierprops Customizes outlier markers. flierprops=props

19. Practical Example: Comparing Student Marks

Let's create a box plot to compare the examination marks of three different classes. We will display the mean, category names and customized box colours.

Complete Python Program

import matplotlib.pyplot as plt

class_a = [45, 50, 55, 60, 65, 70, 75, 80]
class_b = [50, 55, 60, 65, 70, 75, 80, 85]
class_c = [35, 40, 45, 50, 55, 60, 65, 70]

data = [class_a, class_b, class_c]

fig, ax = plt.subplots(figsize=(9, 6))

result = ax.boxplot(
    data,
    tick_labels=["Class A", "Class B", "Class C"],
    patch_artist=True,
    showmeans=True,
    showfliers=True,
    notch=False
)

colors = [
    "#93c5fd",
    "#86efac",
    "#fcd34d"
]

for patch, color in zip(result["boxes"], colors):
    patch.set_facecolor(color)

ax.set_title("Student Marks Comparison")
ax.set_xlabel("Classes")
ax.set_ylabel("Marks")

ax.grid(axis="y", linestyle="--", alpha=0.5)

plt.show()

Expected Output

Student Marks Comparison

Three box plots are displayed:

Class A : Blue
Class B : Green
Class C : Yellow

The chart shows:
- Median marks
- First and third quartiles
- Whisker ranges
- Mean markers
- Possible outliers

The three classes can be compared visually.

Understanding the Result

The box plot helps compare the distribution of marks across the three classes. We can observe differences in their medians, middle 50% ranges and overall spread.

20. Best Practices for Box Plots

  • Use box plots to understand the distribution of numerical data.
  • Use clear category labels when comparing multiple datasets.
  • Display mean values when they provide useful information.
  • Use colours consistently across categories.
  • Check possible outliers before making conclusions.
  • Choose suitable whisker settings for your analysis.
  • Use horizontal box plots when category labels are long.
  • Explain the median and quartiles when presenting results.
Important: A box plot summarizes a dataset. It does not display every individual observation. Use other charts when you need to show the complete distribution or individual data points.

21. Common Mistakes and Solutions

Common Mistake Solution
Passing incorrectly structured data. Pass a list or sequence of numerical datasets.
Category labels do not match datasets. Provide one label for every box plot.
Box fill colour is not visible. Set patch_artist=True.
Outliers are not displayed. Check that showfliers=True.
Mean marker is missing. Set showmeans=True.
Horizontal orientation does not work. Use the supported orientation option for your Matplotlib version.
Older Matplotlib version rejects tick_labels. Use the older labels parameter if required.

22. Practice Questions

Beginner Level

  1. What is a box and whisker plot?
  2. What are the five values used in a five-number summary?
  3. What is the median?
  4. What is the purpose of the IQR?
  5. Which Matplotlib function creates a box plot?

Intermediate Level

  1. Explain the difference between Q1 and Q3.
  2. How are possible outliers identified?
  3. What is the purpose of the whis parameter?
  4. How can you create a horizontal box plot?
  5. How do you display the mean value?
  6. What is the purpose of patch_artist?

Practical Tasks

  1. Create a box plot for student examination marks.
  2. Compare marks from three different classes.
  3. Create a horizontal box plot.
  4. Display mean values and possible outliers.
  5. Create a notched box plot.
  6. Customize box, median and whisker colours.

Summary

A box and whisker plot is a statistical chart used to summarize numerical data. It displays the median, quartiles, whiskers and possible outliers, helping users understand the distribution and spread of a dataset.

The five-number summary includes the minimum, first quartile, median, third quartile and maximum. The interquartile range is calculated by subtracting Q1 from Q3 and is commonly used to identify possible outliers.

Matplotlib provides the plt.boxplot() function to create box plots. Parameters such as notch, showmeans, showfliers, whis and tick_labels help control the chart's behaviour and presentation.

Box plot components can be customized using properties such as boxprops, medianprops, whiskerprops, capprops and flierprops. The object-oriented API also provides control through the ax.boxplot() method.