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

Text Customization in Matplotlib

In this lesson, you will learn how to customize text elements in Matplotlib charts using font properties, colours, alignment, rotation, and text formatting options.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Understand text customization in Matplotlib.
  • Change font size and font family.
  • Customize text colour and font weight.
  • Apply italic and bold text styles.
  • Control horizontal and vertical text alignment.
  • Rotate text in different directions.
  • Customize text using font dictionaries.
  • Use text formatting with the object-oriented API.

2. Introduction to Text Customization

Text customization is an important part of data visualization. Matplotlib allows developers to change the appearance of text displayed in charts, including titles, axis labels, annotations, and other text elements.

By using different text properties, we can make charts more readable, attractive, and professional.

Example: Sales Performance Report

Suppose a company wants to display its sales performance using a chart. The title can be displayed in bold text, axis labels can use different font sizes, and important values can be highlighted using different colours.

These formatting options help users identify important information quickly.

3. Changing Font Size

The fontsize parameter is used to change the size of text in a Matplotlib chart. It can be applied to titles, labels, and text elements.

Basic Syntax

plt.title("Chart Title", fontsize=18)

plt.xlabel("X-axis Label", fontsize=14)

plt.ylabel("Y-axis Label", fontsize=14)

Example: Custom Font Size

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 150, 130, 180]

plt.plot(months, sales, marker="o")

plt.title("Monthly Sales Report", fontsize=20)
plt.xlabel("Months", fontsize=14)
plt.ylabel("Sales", fontsize=14)

plt.show()

Expected Output

Figure 1: Monthly Sales Report

A line chart will be displayed.

Title Font Size      : 20
X-axis Label Size    : 14
Y-axis Label Size    : 14

The chart title appears larger than the axis labels.
Tip: Use larger font sizes for chart titles and suitable font sizes for axis labels to maintain a clear hierarchy.

4. Changing Font Family

Matplotlib allows you to change the font family used for displaying text. Different font families can be used to customize the appearance of chart text.

Basic Syntax

plt.title(
    "Chart Title",
    fontfamily="serif"
)

Example: Using Different Font Families

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 150, 130, 180]

plt.plot(months, sales)

plt.title(
    "Monthly Sales Report",
    fontfamily="serif",
    fontsize=18
)

plt.xlabel(
    "Months",
    fontfamily="sans-serif"
)

plt.ylabel(
    "Sales",
    fontfamily="monospace"
)

plt.show()

Expected Output

Figure 2: Monthly Sales Report

A line chart will be displayed.

Title Font Family  : Serif
X-axis Font Family : Sans-serif
Y-axis Font Family : Monospace

Different font families are applied to chart text.
Font Family Description
serif Displays text with small decorative strokes.
sans-serif Displays clean text without decorative strokes.
monospace Displays characters using equal character widths.
cursive Uses a handwriting-style font family when available.
fantasy Uses decorative font styles when available.

5. Changing Font Weight

The fontweight parameter controls the thickness of text. It can be used to highlight important titles and labels.

Basic Syntax

plt.title(
    "Chart Title",
    fontweight="bold"
)

Example: Bold Chart Title

import matplotlib.pyplot as plt

students = ["Amit", "Neha", "Rahul", "Priya"]
marks = [75, 88, 65, 92]

plt.plot(students, marks, marker="o")

plt.title(
    "Student Performance",
    fontsize=18,
    fontweight="bold"
)

plt.xlabel("Students")
plt.ylabel("Marks")

plt.show()

Expected Output

Figure 3: Student Performance

A line chart will be displayed.

Title:
Student Performance

Font Weight:
Bold

X-axis Label:
Students

Y-axis Label:
Marks
Font Weight Description
normal Displays normal text thickness.
bold Displays bold text.
light Displays lighter text.
heavy Displays heavier text.
black Displays very thick text when supported.

6. Changing Text Colour

The color parameter is used to change the colour of text in Matplotlib charts. Different colours can be applied to titles, labels, and other text elements.

Basic Syntax

plt.title(
    "Chart Title",
    color="blue"
)

Example: Different Text Colours

import matplotlib.pyplot as plt

products = ["Laptop", "Mobile", "Tablet", "Monitor"]
prices = [55000, 25000, 18000, 30000]

plt.bar(products, prices)

plt.title(
    "Product Price Comparison",
    color="blue",
    fontsize=18
)

plt.xlabel(
    "Products",
    color="green"
)

plt.ylabel(
    "Price",
    color="red"
)

plt.show()

Expected Output

Figure 4: Product Price Comparison

A bar chart will be displayed.

Title Colour      : Blue
X-axis Label      : Green
Y-axis Label      : Red

Different colours are applied to the chart text.

7. Applying Italic Text Style

The fontstyle parameter is used to change the style of text. It supports normal, italic, and oblique styles.

Basic Syntax

plt.title(
    "Chart Title",
    fontstyle="italic"
)

Example: Italic Title

import matplotlib.pyplot as plt

years = [2022, 2023, 2024, 2025]
revenue = [20000, 30000, 45000, 60000]

plt.plot(years, revenue, marker="o")

plt.title(
    "Company Revenue Growth",
    fontstyle="italic",
    fontsize=18
)

plt.xlabel("Years")
plt.ylabel("Revenue")

plt.show()

Expected Output

Figure 5: Company Revenue Growth

A line chart will be displayed.

Title:
Company Revenue Growth

Font Style:
Italic

X-axis Label:
Years

Y-axis Label:
Revenue
Font Style Description
normal Displays normal text.
italic Displays italic text.
oblique Displays slanted text.

8. Text Alignment

Matplotlib provides horizontal and vertical alignment options to control the position of text. The horizontalalignment and verticalalignment parameters are used with text elements.

Basic Syntax

plt.text(
    2,
    20,
    "Important Point",
    horizontalalignment="center",
    verticalalignment="center"
)

Example: Text Alignment

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 15, 30]

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

plt.text(
    2,
    20,
    "Maximum Value",
    horizontalalignment="center",
    verticalalignment="bottom"
)

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

plt.show()

Expected Output

Figure 6: Text Alignment Example

A line chart will be displayed.

The text "Maximum Value" appears
at the specified data position.

Horizontal Alignment : Center
Vertical Alignment   : Bottom
Parameter Available Values
horizontalalignment left, center, right
verticalalignment top, center, bottom, baseline

9. Rotating Text

The rotation parameter is used to rotate text by a specified angle. It is useful when displaying long category names or labels.

Basic Syntax

plt.xticks(rotation=45)

Example: Rotating X-axis Labels

import matplotlib.pyplot as plt

products = [
    "Laptop",
    "Mobile",
    "Tablet",
    "Keyboard",
    "Monitor"
]

sales = [50, 80, 40, 65, 55]

plt.bar(products, sales)

plt.title("Product Sales Report")
plt.xlabel("Products")
plt.ylabel("Sales")

plt.xticks(rotation=45)

plt.show()

Expected Output

Figure 7: Product Sales Report

A bar chart will be displayed.

X-axis Labels:
Laptop
Mobile
Tablet
Keyboard
Monitor

Rotation:
45 degrees

The category labels are displayed at an angle.
Tip: Text rotation is useful when category names are long and overlap with one another.

10. Using Font Properties Dictionary

Matplotlib allows you to define multiple font properties using a dictionary. This makes it easier to reuse the same text formatting in different parts of a chart.

Example: Font Dictionary

import matplotlib.pyplot as plt

font_properties = {
    "family": "serif",
    "color": "darkblue",
    "weight": "bold",
    "size": 16
}

months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 150, 130, 180]

plt.plot(months, sales, marker="o")

plt.title(
    "Monthly Sales Report",
    fontdict=font_properties
)

plt.xlabel("Months")
plt.ylabel("Sales")

plt.show()

Expected Output

Figure 8: Monthly Sales Report

A line chart will be displayed.

Font Properties:
Family : Serif
Colour : Dark Blue
Weight : Bold
Size   : 16

The font dictionary applies multiple
formatting properties to the chart title.
Important: Font dictionary keys must use supported Matplotlib text properties. Use the appropriate property names for the text element you are customizing.

11. Text Customization Using Object-Oriented API

Matplotlib also supports text customization through the object-oriented API. You can use Axes methods to customize titles, labels, and text elements.

Example: Object-Oriented Text Customization

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 150, 130, 180]

fig, ax = plt.subplots()

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

ax.set_title(
    "Monthly Sales Report",
    fontsize=18,
    color="blue",
    fontweight="bold"
)

ax.set_xlabel(
    "Months",
    fontsize=14
)

ax.set_ylabel(
    "Sales",
    fontsize=14
)

plt.show()

Expected Output

Figure 9: Monthly Sales Report

A line chart will be displayed.

Title:
Monthly Sales Report
Font Size   : 18
Colour      : Blue
Font Weight : Bold

X-axis Label: Months
Y-axis Label: Sales

The chart uses the object-oriented API.

12. Common Mistakes in Text Customization

1. Using Very Small Font Sizes

Very small font sizes can make chart titles and labels difficult to read.

2. Using Too Many Colours

Using too many different colours can make a chart confusing.

3. Incorrect Font Property Names

Always use valid Matplotlib text properties such as fontsize, fontweight, and fontstyle.

4. Overlapping Text

Long labels can overlap when there is not enough space. Use text rotation or adjust the layout.

5. Using Inconsistent Formatting

Use consistent font sizes, font families, and colours across related charts.

Important: Text formatting should improve readability. Avoid unnecessary styling that distracts users from the actual data.

13. Classroom Practical Activity

Activity: Create a Customized Employee Performance Chart

Create a line chart showing the performance scores of five employees. Apply different text formatting properties to the chart.

Sample Data

employees = ["Amit", "Neha", "Rahul", "Priya", "Sagar"]
scores = [75, 88, 65, 92, 80]

Instructions

  1. Import Matplotlib pyplot.
  2. Create a line chart using plt.plot().
  3. Add the title "Employee Performance Report".
  4. Set the title font size to 20.
  5. Apply bold font weight to the title.
  6. Change the title colour to blue.
  7. Add X-axis and Y-axis labels.
  8. Rotate X-axis labels by 45 degrees.
  9. Display the chart using plt.show().

Practice Questions

  1. What is text customization in Matplotlib?
  2. Which parameter changes the font size?
  3. How can you change the font family?
  4. What is the purpose of fontweight?
  5. Which parameter is used to change text colour?
  6. How can you apply italic text style?
  7. What is the purpose of horizontal alignment?
  8. How can you rotate X-axis labels?
  9. What is a font properties dictionary?
  10. How can you customize text using the Axes object?

Summary

In this lesson, you learned how to customize text elements in Matplotlib charts. You explored font size, font family, font weight, text colour, italic styles, alignment, and text rotation.

You also learned how to use font dictionaries and apply text formatting through the object-oriented API. These features help create clear, readable, and professional data visualizations.

Proper text customization improves chart presentation and helps users understand important information quickly.