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

Basic Text in Matplotlib

Learn how to add text inside Matplotlib figures and charts. Understand text positioning, font properties, alignment, rotation, and how to make your visualisations more informative.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand why text is used in Matplotlib visualisations.
  • Use plt.text() to add text to a plot.
  • Use ax.text() with the object-oriented interface.
  • Control text position using X and Y coordinates.
  • Customize font size, colour, family, and weight.
  • Apply horizontal and vertical alignment.
  • Rotate text and add background boxes.
  • Place text inside charts to highlight important information.

2. Introduction to Text in Matplotlib

Text is an important part of data visualisation. A chart may contain correct data, but without proper information, users may not understand what the chart represents.

Matplotlib provides text functions that allow us to display messages, labels, descriptions, and additional information at specific positions inside a figure or axes.

Why do we use text?

  • To explain important values in a chart.
  • To highlight maximum and minimum values.
  • To display additional information.
  • To make charts easier to understand.
  • To identify important points in a visualisation.
Highest Value 20 35 30 55 70 X Axis Y Axis

Text labels help users understand important values in a chart.

3. Using plt.text()

The plt.text() function is used to add text at a specific X and Y coordinate in the current axes.

Its basic syntax is:

plt.text(x, y, text)

Here:

  • x represents the horizontal position.
  • y represents the vertical position.
  • text represents the message to display.

Example: Adding basic text

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [10, 20, 15, 30])

plt.text(2, 20, "Important Point")

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

plt.show()

Output

Line chart displayed with the text
"Important Point" at coordinate (2, 20).

Title: Basic Text Example
X-axis: X Values
Y-axis: Y Values
Tip: The text position is based on the data coordinates of the axes by default. If the specified position is outside the visible axis limits, the text may not appear in the visible chart area.

4. Using ax.text()

Matplotlib also provides ax.text(), which belongs to the object-oriented interface. It adds text to a particular Axes object.

This approach is useful when working with multiple charts or subplots because we can control exactly which axes receives the text.

Example: Using ax.text()

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot([1, 2, 3, 4], [10, 20, 15, 30])

ax.text(2, 20, "Sales Increased")

ax.set_title("Sales Performance")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")

plt.show()

Output

A line chart is displayed with the title
"Sales Performance".

The text "Sales Increased" appears
at the coordinate (2, 20).

plt.text() vs ax.text()

plt.text() ax.text()
Uses the current axes. Uses a specific Axes object.
Works with the pyplot interface. Works with the object-oriented interface.
Useful for simple plots. Useful for multiple axes and complex figures.
Syntax: plt.text() Syntax: ax.text()

5. Understanding Text Position

Text position is controlled using X and Y coordinates. These coordinates determine where the text appears inside the axes.

For example, plt.text(2, 10, "Hello") displays the text at X coordinate 2 and Y coordinate 10.

Hello Matplotlib X = 2 Y = 2 X Coordinate Y Coordinate

The X and Y coordinates determine the text anchor position.

Example: Multiple text positions

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [10, 20, 30, 40])

plt.text(1, 10, "Point One")
plt.text(2, 20, "Point Two")
plt.text(3, 30, "Point Three")
plt.text(4, 40, "Point Four")

plt.title("Multiple Text Positions")
plt.show()

Output

A line chart is displayed with four text labels:

Point One   at (1, 10)
Point Two   at (2, 20)
Point Three at (3, 30)
Point Four  at (4, 40)

6. Customizing Text Font Properties

Matplotlib allows us to customize the appearance of text using different font properties. We can change font size, colour, family, and weight.

6.1 Font Size

Use fontsize to control the size of the text.

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [10, 20, 30])

plt.text(1, 15, "Small Text", fontsize=10)
plt.text(1, 20, "Medium Text", fontsize=16)
plt.text(1, 25, "Large Text", fontsize=22)

plt.title("Font Size Example")
plt.show()

Output

The chart displays three text labels
with different font sizes:

Small Text  - 10
Medium Text - 16
Large Text  - 22

6.2 Font Colour

Use color to change the text colour. Matplotlib supports common colour names, hexadecimal values, and other colour formats.

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [10, 20, 30])

plt.text(1, 15, "Red Text", color="red")
plt.text(1, 20, "Blue Text", color="blue")
plt.text(1, 25, "Green Text", color="green")

plt.title("Text Colour Example")
plt.show()

Output

The chart displays three text labels:

Red Text   - Red colour
Blue Text  - Blue colour
Green Text - Green colour

6.3 Font Weight

The fontweight property controls the thickness of the text. Common values include normal, bold, and light.

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [10, 20, 30])

plt.text(1, 15, "Normal Text", fontweight="normal")
plt.text(1, 20, "Bold Text", fontweight="bold")
plt.text(1, 25, "Light Text", fontweight="light")

plt.title("Font Weight Example")
plt.show()

Output

The chart displays text with different font weights:

Normal Text - Normal thickness
Bold Text   - Bold thickness
Light Text  - Light thickness

6.4 Font Family

Use fontfamily to specify the font family for text. The available fonts depend on the fonts installed on your system.

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [10, 20, 30])

plt.text(1, 15, "Serif Font",
         fontfamily="serif")

plt.text(1, 20, "Sans Serif Font",
         fontfamily="sans-serif")

plt.text(1, 25, "Monospace Font",
         fontfamily="monospace")

plt.title("Font Family Example")
plt.show()

Output

The chart displays three text labels
using different font families:

Serif Font
Sans Serif Font
Monospace Font
Tip: You can combine font properties in one plt.text() or ax.text() call.

7. Text Alignment

Text alignment controls how text is positioned around its anchor coordinate. Matplotlib provides horizontal and vertical alignment.

7.1 Horizontal Alignment

Use horizontalalignment or its shorter form ha to align text horizontally.

Value Description
left Text starts from the anchor position.
center Text is centered around the anchor position.
right Text ends at the anchor position.
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [10, 20, 30])

plt.text(2, 15, "Left Aligned",
         ha="left")

plt.text(2, 20, "Center Aligned",
         ha="center")

plt.text(2, 25, "Right Aligned",
         ha="right")

plt.title("Horizontal Alignment")
plt.show()

Output

The chart displays three text labels
with different horizontal alignments:

Left Aligned
Center Aligned
Right Aligned

7.2 Vertical Alignment

Use verticalalignment or va to control the vertical position of text around its anchor.

Value Description
top Aligns the top of the text with the anchor.
center Centers the text vertically around the anchor.
bottom Aligns the bottom of the text with the anchor.
baseline Aligns the text baseline with the anchor.
center_baseline Aligns the center of the text's baseline area.
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot([1, 2, 3], [10, 20, 30])

ax.text(2, 15, "Top Aligned",
        va="top")

ax.text(2, 20, "Center Aligned",
        va="center")

ax.text(2, 25, "Bottom Aligned",
        va="bottom")

ax.set_title("Vertical Alignment")
plt.show()

Output

The chart displays text using different
vertical alignment settings:

Top Aligned
Center Aligned
Bottom Aligned

8. Rotating Text

Matplotlib allows us to rotate text using the rotation property. This is useful when labels need to fit into limited space.

The rotation value is specified in degrees. For example, rotation=45 rotates text by 45 degrees.

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [10, 20, 30, 40])

plt.text(1, 10, "Normal Text",
         rotation=0)

plt.text(2, 20, "Rotated 45",
         rotation=45)

plt.text(3, 30, "Rotated 90",
         rotation=90)

plt.title("Text Rotation Example")
plt.show()

Output

The chart displays three text labels:

Normal Text  - 0 degrees
Rotated 45   - 45 degrees
Rotated 90   - 90 degrees
Tip: Rotation is useful for long labels, date labels, and category names that would otherwise overlap.

9. Adding Background Boxes to Text

The bbox property adds a background box behind text. It helps important messages stand out from the chart.

You can customize the box using properties such as facecolor, edgecolor, boxstyle, and alpha.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot([1, 2, 3, 4], [10, 20, 15, 30])

ax.text(
    2,
    20,
    "Important Information",
    fontsize=12,
    color="darkblue",
    bbox={
        "facecolor": "yellow",
        "edgecolor": "black",
        "boxstyle": "round",
        "alpha": 0.7
    }
)

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

Output

A line chart is displayed with the text
"Important Information".

The text appears inside a rounded yellow
background box with a black border.
Important Success Information Yellow background Green background Blue background

Background boxes can highlight important text in a visualisation.

10. Complete Example: Student Performance Chart

Let's combine the concepts we have learned and create a student performance chart. We will add text labels, font properties, alignment, and a background box.

import matplotlib.pyplot as plt

students = ["Amit", "Rahul", "Priya", "Sneha", "Neha"]
marks = [65, 78, 92, 85, 70]

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

ax.bar(students, marks, color="skyblue")

ax.text(
    2,
    95,
    "Highest Score",
    ha="center",
    fontsize=12,
    fontweight="bold",
    color="green",
    bbox={
        "facecolor": "white",
        "edgecolor": "green",
        "boxstyle": "round"
    }
)

for index, mark in enumerate(marks):
    ax.text(
        index,
        mark + 1,
        str(mark),
        ha="center",
        fontsize=11,
        fontweight="bold"
    )

ax.set_title("Student Performance")
ax.set_xlabel("Students")
ax.set_ylabel("Marks")
ax.set_ylim(0, 110)

plt.show()

Output

Bar chart displayed:

Amit  - 65
Rahul - 78
Priya - 92
Sneha - 85
Neha  - 70

Title: Student Performance

Each bar displays its marks above it.
"Highest Score" appears above Priya's bar
inside a highlighted text box.
Practical Note: In this example, the text for the highest score is positioned using the known maximum value. For dynamic datasets, calculate the maximum value and its index before placing the label.

11. Important Text Parameters

The following table contains commonly used parameters for plt.text() and ax.text().

Parameter Purpose Example
x Horizontal text position. x=2
y Vertical text position. y=20
fontsize Controls text size. fontsize=16
color Changes text colour. color="red"
fontweight Controls font thickness. fontweight="bold"
fontfamily Sets font family. fontfamily="serif"
ha Horizontal alignment. ha="center"
va Vertical alignment. va="center"
rotation Rotates text. rotation=45
bbox Adds a background box. bbox={"facecolor": "yellow"}
alpha Controls transparency. alpha=0.7

12. Practical Activity

Activity: Create a Monthly Sales Chart

Create a bar chart showing monthly sales and add text labels above every bar.

Given data:

months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [12000, 15000, 18000, 14000, 22000]

Your tasks:

  1. Create a bar chart using the given data.
  2. Add a title named Monthly Sales Report.
  3. Display each sales value above its bar.
  4. Use bold text for the sales values.
  5. Highlight the highest sales value using a background box.
  6. Set appropriate X-axis and Y-axis labels.

13. Practice Questions

  1. What is the purpose of text in Matplotlib?
  2. What is the difference between plt.text() and ax.text()?
  3. How do you specify the X and Y position of text?
  4. Which parameter changes the font size?
  5. How can you make text bold?
  6. What is the purpose of horizontal alignment?
  7. How can you rotate text by 45 degrees?
  8. What is the use of the bbox parameter?
  9. How can you change the text colour?
  10. Why is text useful in data visualisation?

Summary

In this lesson, we learned how to add text to Matplotlib charts using plt.text() and ax.text(). These functions allow us to display messages and additional information at specific coordinates inside an axes.

We explored text positioning through X and Y coordinates and learned how to customize font size, font colour, font family, and font weight. These properties help us make text clear and readable.

We also covered horizontal and vertical alignment, text rotation, and background boxes using the bbox property. These features are useful when highlighting important information in charts.

Finally, we combined these concepts in a student performance chart and practiced adding labels to individual bars. In the next lesson, we will learn how to create smart annotations that point to specific data points and explain important chart information.