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

Smart Annotations in Matplotlib

Learn how to highlight important data points using annotations. Add descriptive labels, arrows, text boxes, and custom positioning to make your charts more informative and easier to understand.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand annotations in Matplotlib.
  • Use plt.annotate() to highlight data points.
  • Use ax.annotate() with the object-oriented interface.
  • Understand the difference between xy and xytext.
  • Add arrows to point towards important values.
  • Customize arrow properties and arrow styles.
  • Control text position using coordinate offsets.
  • Use text boxes and bounding boxes with annotations.
  • Create practical annotations for real-world charts.

2. Introduction to Annotations

An annotation is a text label that provides additional information about a particular location or data point in a chart.

Sometimes a chart contains an important value, such as the highest sales, lowest temperature, maximum profit, or sudden decrease. An annotation helps us highlight that information clearly.

Matplotlib provides the annotate() function to add text and optionally connect it to a point using an arrow.

Why are annotations useful?

  • Highlight maximum and minimum values.
  • Explain sudden increases or decreases.
  • Identify important events in time-series charts.
  • Display additional information about a data point.
  • Guide the viewer's attention to important information.
Highest Sales: 90 Jan Feb Mar Apr May Month Sales

An annotation uses text and an arrow to highlight an important data point.

3. Understanding annotate()

The annotate() function adds a text annotation to a specific location in a chart. It can also draw an arrow from the text position to the selected data point.

Basic syntax:

plt.annotate(
    text,
    xy=(x, y),
    xytext=(text_x, text_y),
    arrowprops=dict()
)

Important arguments:

  • text: The message displayed in the annotation.
  • xy: The point that the annotation refers to.
  • xytext: The position where annotation text appears.
  • arrowprops: Controls the arrow appearance.

Example: Basic annotation

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 35, 50]

plt.plot(x, y, marker="o")

plt.annotate(
    "Highest Value",
    xy=(5, 50)
)

plt.title("Basic Annotation Example")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Output

A line chart is displayed with five data points.

The text "Highest Value" is placed
at the data point (5, 50).

Title: Basic Annotation Example
X-axis: X Values
Y-axis: Y Values
Tip: If you provide only xy, the annotation text is placed at the referenced point by default. Use xytext when you want to position the text separately.

4. Understanding xy and xytext

The two most important arguments in an annotation are xy and xytext.

xy

Specifies the coordinates of the data point that you want to explain or highlight.

xytext

Specifies the coordinates where the annotation text should appear. If omitted, the text is placed at the referenced point.

xy = (5, 40) Important Point xytext = text position X Coordinate Y Coordinate

xy identifies the target point, while xytext identifies the text location.

Example: Separate text and data positions

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 35, 50]

plt.plot(x, y, marker="o")

plt.annotate(
    "Highest Point",
    xy=(5, 50),
    xytext=(3, 55)
)

plt.title("Annotation Position Example")
plt.show()

Output

A line chart is displayed.

Target data point:
xy = (5, 50)

Annotation text position:
xytext = (3, 55)

Text: Highest Point
Important: By default, xytext uses the same coordinate system as xy. You can change the text coordinate system using textcoords.

5. Adding Arrows to Annotations

Arrows help users understand exactly which data point an annotation describes. The arrowprops argument is used to customize the arrow.

Basic arrow syntax:

arrowprops=dict(
    arrowstyle="->",
    color="red",
    linewidth=2
)

Example: Annotation with an arrow

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 35, 50]

plt.plot(x, y, marker="o")

plt.annotate(
    "Maximum Value",
    xy=(5, 50),
    xytext=(3, 60),
    arrowprops=dict(
        arrowstyle="->",
        color="red",
        linewidth=2
    )
)

plt.title("Annotation with Arrow")
plt.show()

Output

A line chart is displayed.

The text "Maximum Value" appears
above the last data point.

A red arrow points from the text
towards the data point (5, 50).

Common arrow styles

Arrow Style Description
-> Simple arrow with an arrowhead.
<- Arrow pointing in the opposite direction.
<-> Arrowheads at both ends.
fancy Fancy arrow shape.
simple Simple filled arrow shape.
wedge Wedge-shaped arrow.
Tip: The arrow style is controlled through arrowstyle. You can also customize its colour, width, and connection style.

6. Customizing Arrow Properties

Matplotlib provides different arrow properties to control how the arrow looks and connects to the target point.

Property Purpose Example
arrowstyle Defines the arrow shape. "->"
color Sets the arrow colour. "red"
linewidth Controls arrow line width. 2
linestyle Sets solid or dashed line style. "dashed"
connectionstyle Controls the connection path. "arc3,rad=0.3"
shrinkA Shortens the arrow near the text. 5
shrinkB Shortens the arrow near the target. 5

Example: Customized arrow

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot([1, 2, 3, 4, 5],
        [10, 20, 15, 35, 50],
        marker="o")

ax.annotate(
    "Important Event",
    xy=(5, 50),
    xytext=(2.5, 55),
    fontsize=12,
    color="darkblue",
    arrowprops=dict(
        arrowstyle="->",
        color="red",
        linewidth=2,
        connectionstyle="arc3,rad=0.2",
        shrinkA=5,
        shrinkB=5
    )
)

ax.set_title("Customized Annotation Arrow")
plt.show()

Output

A line chart is displayed with an annotation.

Text: Important Event
Text colour: Dark blue
Arrow colour: Red
Arrow width: 2
Arrow connection: Curved

The arrow points towards the data point (5, 50).

7. Understanding textcoords

The textcoords argument controls the coordinate system used for the annotation text position specified by xytext.

It is especially useful when you want to place text a fixed distance away from a data point instead of calculating a new data coordinate.

Coordinate System Description
offset points Places text using an offset measured in points from the target.
offset pixels Places text using an offset measured in display pixels.
data Uses data coordinates.
axes fraction Uses fractional coordinates relative to the axes.
figure fraction Uses fractional coordinates relative to the figure.

Example: Using offset points

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 35, 50]

fig, ax = plt.subplots()

ax.plot(x, y, marker="o")

ax.annotate(
    "Highest Value",
    xy=(5, 50),
    xytext=(20, 20),
    textcoords="offset points",
    arrowprops=dict(
        arrowstyle="->",
        color="red"
    )
)

ax.set_title("Text Offset Example")
plt.show()

Output

A line chart is displayed.

Target point: (5, 50)

Annotation text is positioned
20 points horizontally and
20 points vertically from the target.

A red arrow connects the text
to the target point.
Tip: offset points is useful when you want consistent spacing between a data point and its annotation, even when the chart is resized.

8. Adding Text Boxes to Annotations

You can use the bbox argument to place annotation text inside a styled background box. This improves readability when annotations appear over lines or other chart elements.

Example: Annotation with a text box

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(
    [1, 2, 3, 4, 5],
    [10, 20, 15, 35, 50],
    marker="o"
)

ax.annotate(
    "Maximum Sales",
    xy=(5, 50),
    xytext=(3, 60),
    fontsize=12,
    color="darkgreen",
    bbox=dict(
        boxstyle="round,pad=0.5",
        facecolor="lightyellow",
        edgecolor="green"
    ),
    arrowprops=dict(
        arrowstyle="->",
        color="green",
        linewidth=2
    )
)

ax.set_title("Annotation with Text Box")
plt.show()

Output

A line chart is displayed.

The text "Maximum Sales" appears
inside a rounded light-yellow box
with a green border.

A green arrow points to the maximum
data point (5, 50).

9. Annotating Multiple Data Points

We can add multiple annotations to the same chart. This is useful when several data points need explanations.

Example: Highlighting multiple values

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [20, 35, 25, 60, 45]

fig, ax = plt.subplots()

ax.plot(
    months,
    sales,
    marker="o",
    linewidth=2
)

ax.annotate(
    "Sales Increased",
    xy=("Feb", 35),
    xytext=("Jan", 50),
    arrowprops=dict(
        arrowstyle="->",
        color="green"
    )
)

ax.annotate(
    "Highest Sales",
    xy=("Apr", 60),
    xytext=("Mar", 75),
    arrowprops=dict(
        arrowstyle="->",
        color="red"
    )
)

ax.set_title("Monthly Sales with Annotations")
ax.set_ylabel("Sales")

plt.show()

Output

A monthly sales line chart is displayed.

January to May sales:
Jan - 20
Feb - 35
Mar - 25
Apr - 60
May - 45

Annotation 1:
Sales Increased - points to February.

Annotation 2:
Highest Sales - points to April.
Important: When adding many annotations, avoid overlapping labels and arrows. Use different text positions and offsets to keep the chart readable.

10. Using ax.annotate()

Similar to ax.text(), Matplotlib provides ax.annotate() for the object-oriented interface. It adds an annotation to a specific Axes object.

This is useful when a figure contains multiple subplots because you can select exactly which axes should display the annotation.

Example: Object-oriented annotation

import matplotlib.pyplot as plt

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

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 35, 50]

ax.plot(x, y, marker="o")

ax.annotate(
    "Maximum Value",
    xy=(5, 50),
    xytext=(3, 60),
    arrowprops=dict(
        arrowstyle="->",
        color="red"
    )
)

ax.set_title("Object-Oriented Annotation")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")

plt.show()

Output

A line chart is displayed using a Figure and Axes object.

The annotation "Maximum Value" appears
above the point (5, 50).

A red arrow connects the annotation
to the maximum value.

plt.annotate() vs ax.annotate()

plt.annotate() ax.annotate()
Uses the current axes. Uses a specific Axes object.
Uses the pyplot interface. Uses the object-oriented interface.
Suitable for simple plots. Suitable for multiple axes and complex figures.

11. Complete Practical Example: Company Revenue

Let's create a company revenue chart and highlight the highest revenue month using a smart annotation.

import matplotlib.pyplot as plt

months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June"
]

revenue = [12000, 15000, 14000, 22000, 18000, 28000]

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

ax.plot(
    months,
    revenue,
    marker="o",
    color="blue",
    linewidth=2
)

max_index = revenue.index(max(revenue))

ax.annotate(
    "Highest Revenue",
    xy=(max_index, revenue[max_index]),
    xytext=(max_index - 1.5, revenue[max_index] + 3000),
    fontsize=11,
    fontweight="bold",
    color="darkgreen",
    bbox=dict(
        boxstyle="round,pad=0.5",
        facecolor="lightyellow",
        edgecolor="green"
    ),
    arrowprops=dict(
        arrowstyle="->",
        color="red",
        linewidth=2
    )
)

ax.set_title("Company Monthly Revenue")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue")

ax.tick_params(axis="x", rotation=25)
ax.grid(True, linestyle="--", alpha=0.5)

plt.tight_layout()
plt.show()

Output

Company Monthly Revenue

January  - 12000
February - 15000
March    - 14000
April    - 22000
May      - 18000
June     - 28000

The highest revenue is 28000 in June.

A highlighted annotation box displays
"Highest Revenue" with a red arrow
pointing towards the June data point.
Practical Note: We used revenue.index(max(revenue)) to find the position of the highest revenue value. This makes the annotation work even when the data changes.

12. Important Annotation Parameters

Parameter Purpose Example
text Annotation message. "Highest Value"
xy Target point coordinates. xy=(5, 50)
xytext Annotation text position. xytext=(3, 60)
textcoords Coordinate system for annotation text. "offset points"
arrowprops Controls arrow appearance. dict(arrowstyle="->")
fontsize Controls annotation text size. fontsize=12
color Sets annotation text colour. color="red"
fontweight Controls text thickness. fontweight="bold"
bbox Adds a background box. bbox=dict(facecolor="yellow")
ha Horizontal text alignment. ha="center"
va Vertical text alignment. va="center"

13. Practical Activity

Activity: Highlight Highest and Lowest Temperature

Create a line chart showing weekly temperatures. Use annotations to highlight the highest and lowest temperatures.

Given data:

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

temperature = [28, 32, 25, 35, 30, 22, 33]

Your tasks:

  1. Create a line chart with markers.
  2. Add the title Weekly Temperature Report.
  3. Find the maximum temperature using Python.
  4. Find the minimum temperature using Python.
  5. Add an annotation for the highest temperature.
  6. Add an annotation for the lowest temperature.
  7. Use arrows to point towards both data points.
  8. Use different text box colours for both annotations.

14. Practice Questions

  1. What is an annotation in Matplotlib?
  2. What is the purpose of plt.annotate()?
  3. What is the difference between xy and xytext?
  4. What is the purpose of arrowprops?
  5. How can you change the arrow colour?
  6. What is the use of textcoords?
  7. How can you add a background box to annotation text?
  8. What is the difference between plt.annotate() and ax.annotate()?
  9. How can you highlight the highest value in a chart?
  10. Why should we avoid overlapping annotations?

Summary

In this lesson, we learned how to create smart annotations in Matplotlib using plt.annotate() and ax.annotate(). Annotations help explain important data points and provide additional information inside charts.

We explored the xy argument to identify the target point and xytext to position annotation text. We also learned how to connect text to data points using arrows.

We customized arrows using properties such as arrowstyle, color, linewidth, and connectionstyle. We also explored coordinate systems using textcoords and added background boxes using bbox.

Finally, we created a practical company revenue chart and highlighted the highest revenue value dynamically. In the next lesson, we will learn how to draw shapes such as rectangles, circles, and arrows directly inside Matplotlib charts.