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

Titles and Labels in Matplotlib

In this lesson, you will learn how to add titles and labels to Matplotlib charts, customize their appearance, and use different formatting options to make data visualizations clear and easy to understand.

1. Learning Objectives

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

  • Understand the importance of titles and labels in Matplotlib.
  • Add a title to a chart using plt.title().
  • Add an X-axis label using plt.xlabel().
  • Add a Y-axis label using plt.ylabel().
  • Customize title and label font properties.
  • Control the position and spacing of titles and labels.
  • Use titles and labels with different types of charts.
  • Apply titles and labels using the object-oriented API.

2. Introduction to Titles and Labels

Titles and labels are important elements of data visualization. They help users understand what information a chart represents. A title describes the purpose of the chart, while axis labels explain the information displayed along the X-axis and Y-axis.

Matplotlib provides different functions to add titles and labels to charts. These functions help make visualizations more meaningful, readable, and professional.

Example: Student Performance Report

Suppose a teacher wants to create a student performance chart. The chart can have the title Student Performance Report. The X-axis can represent student names, and the Y-axis can represent their marks.

By adding a proper title and axis labels, users can understand the chart without requiring additional explanations.

3. Adding a Title to a Chart

A title describes the main purpose or subject of a chart. Matplotlib provides the plt.title() function to add a title to a visualization.

Basic Syntax

plt.title("Chart Title")

Example: Adding a Chart Title

import matplotlib.pyplot as plt

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

plt.plot(months, sales)

# Add chart title
plt.title("Monthly Sales Report")

plt.show()

Expected Output

Figure 1: Monthly Sales Report

A line chart will be displayed.

Chart Title : Monthly Sales Report
X-axis      : Jan, Feb, Mar, Apr
Y-axis      : Sales values

The title appears at the top of the chart.

In this example, plt.title() adds "Monthly Sales Report" at the top of the line chart.

4. Adding an X-axis Label

The X-axis is the horizontal axis of a chart. It usually represents categories, dates, months, names, or other independent values.

Matplotlib provides the plt.xlabel() function to add a label to the horizontal axis.

Basic Syntax

plt.xlabel("X-axis Label")

Example: Adding an X-axis Label

import matplotlib.pyplot as plt

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

plt.plot(months, sales)

plt.title("Monthly Sales Report")

# Add X-axis label
plt.xlabel("Months")

plt.show()

Expected Output

Figure 2: Monthly Sales Report

A line chart will be displayed.

Chart Title : Monthly Sales Report
X-axis Label: Months

The word "Months" appears below the horizontal axis.
Tip: Use meaningful X-axis labels such as Months, Years, Students, Products, or Dates depending on the data.

5. Adding a Y-axis Label

The Y-axis is the vertical axis of a chart. It generally represents numerical values such as sales, marks, temperature, revenue, or quantity.

Matplotlib provides the plt.ylabel() function to add a label to the vertical axis.

Basic Syntax

plt.ylabel("Y-axis Label")

Example: Adding a Y-axis Label

import matplotlib.pyplot as plt

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

plt.plot(months, sales)

plt.title("Monthly Sales Report")
plt.xlabel("Months")

# Add Y-axis label
plt.ylabel("Sales")

plt.show()

Expected Output

Figure 3: Monthly Sales Report

A line chart will be displayed.

Chart Title : Monthly Sales Report
X-axis Label: Months
Y-axis Label: Sales

The word "Sales" appears beside the vertical axis.

6. Complete Example: Titles and Labels

In this example, we combine the title, X-axis label, and Y-axis label in a single Matplotlib chart.

Python Code

import matplotlib.pyplot as plt

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

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

# Add title
plt.title("Monthly Sales Report")

# Add X-axis label
plt.xlabel("Months")

# Add Y-axis label
plt.ylabel("Sales")

# Display chart
plt.show()

Expected Output

Figure 4: Monthly Sales Report

A line chart with the following details:

Title       : Monthly Sales Report
X-axis Label: Months
Y-axis Label: Sales

Data:
Jan = 100
Feb = 150
Mar = 130
Apr = 180
May = 220

The chart displays monthly sales values with markers.

7. Customizing the Chart Title

Matplotlib allows you to customize the appearance of a chart title. You can change its font size, colour, font weight, alignment, and spacing.

Important Title Parameters

Parameter Description
fontsize Changes the font size of the title.
color Changes the title text colour.
fontweight Controls the thickness of the title text.
loc Sets the title position to left, center, or right.
pad Controls the padding between the title and the axes.

Example: Customized Title

import matplotlib.pyplot as plt

days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
temperature = [25, 28, 27, 30, 32]

plt.plot(days, temperature, marker="o")

plt.title(
    "Weekly Temperature Report",
    fontsize=18,
    color="blue",
    fontweight="bold",
    loc="center",
    pad=20
)

plt.xlabel("Days")
plt.ylabel("Temperature (°C)")

plt.show()

Expected Output

Figure 5: Weekly Temperature Report

A line chart will be displayed.

Title:
Weekly Temperature Report

Title Formatting:
Font Size   : 18
Colour      : Blue
Font Weight : Bold
Position    : Center
Padding     : 20

X-axis Label: Days
Y-axis Label: Temperature (°C)
Tip: Use a suitable font size and readable colour to make the chart title clear and professional.

8. Customizing X-axis and Y-axis Labels

Matplotlib also allows you to customize axis labels. You can change the font size, text colour, font weight, and distance between labels and axes.

Example: Customized Axis Labels

import matplotlib.pyplot as plt

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

plt.bar(products, prices, color="skyblue")

plt.title("Product Price Comparison")

plt.xlabel(
    "Products",
    fontsize=14,
    color="green",
    fontweight="bold"
)

plt.ylabel(
    "Price (Rs.)",
    fontsize=14,
    color="red",
    fontweight="bold"
)

plt.show()

Expected Output

Figure 6: Product Price Comparison

A bar chart will be displayed.

Chart Title:
Product Price Comparison

X-axis Label:
Products
Font Size   : 14
Colour      : Green
Font Weight : Bold

Y-axis Label:
Price (Rs.)
Font Size   : 14
Colour      : Red
Font Weight : Bold

9. Controlling Title and Label Spacing

Matplotlib provides spacing parameters to control the distance between titles, labels, and the plotting area.

Parameter Used With Purpose
pad plt.title() Controls the space between the title and the axes.
labelpad plt.xlabel() and plt.ylabel() Controls the distance between axis labels and axes.

Example: Using Padding

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,
    pad=20
)

plt.xlabel(
    "Students",
    labelpad=12
)

plt.ylabel(
    "Marks",
    labelpad=12
)

plt.show()

Expected Output

Figure 7: Student Performance

A line chart will be displayed.

Title:
Student Performance
Title Padding: 20

X-axis Label:
Students
Label Padding: 12

Y-axis Label:
Marks
Label Padding: 12

The padding values control the spacing
between the text and the plotting area.

10. Titles and Labels Using the Object-Oriented API

Matplotlib also supports an object-oriented approach. In this approach, you create Figure and Axes objects and use Axes methods to add titles and labels.

Example: Using Axes Methods

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr"]
revenue = [20000, 25000, 22000, 30000]

# Create Figure and Axes
fig, ax = plt.subplots()

# Plot data
ax.plot(months, revenue, marker="o")

# Add title
ax.set_title("Monthly Revenue Report")

# Add axis labels
ax.set_xlabel("Months")
ax.set_ylabel("Revenue (Rs.)")

# Display chart
plt.show()

Expected Output

Figure 8: Monthly Revenue Report

A line chart will be displayed.

Chart Title : Monthly Revenue Report
X-axis Label: Months
Y-axis Label: Revenue (Rs.)

The chart is created using the object-oriented API.
Pyplot Function Axes Method Purpose
plt.title() ax.set_title() Adds the chart title.
plt.xlabel() ax.set_xlabel() Adds the X-axis label.
plt.ylabel() ax.set_ylabel() Adds the Y-axis label.

11. Common Mistakes When Using Titles and Labels

1. Forgetting to Add a Chart Title

A chart without a title may not clearly explain what information it represents.

2. Using Unclear Axis Labels

Avoid labels such as X, Y, or Data when meaningful descriptions are available.

3. Using Very Small Font Sizes

Very small fonts can make titles and labels difficult to read.

4. Missing Measurement Units

When displaying values such as temperature, price, or distance, include the appropriate measurement units.

5. Confusing Pyplot and Axes Methods

When using the object-oriented approach, use ax.set_title(), ax.set_xlabel(), and ax.set_ylabel().

Important: Always use clear and meaningful titles and labels. Incorrect or missing labels can make a chart difficult to understand.

12. Classroom Practical Activity

Activity: Create a Student Marks Chart

Create a line chart showing the marks of five students. Add a suitable chart title, X-axis label, and Y-axis label.

Sample Data

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

Instructions

  1. Import the Matplotlib library.
  2. Create a line chart using plt.plot().
  3. Add the title "Student Marks Report".
  4. Set the X-axis label to "Students".
  5. Set the Y-axis label to "Marks".
  6. Customize the title font size and colour.
  7. Display the chart using plt.show().

Practice Questions

  1. What is the purpose of plt.title()?
  2. Which function is used to add an X-axis label?
  3. Which function is used to add a Y-axis label?
  4. How can you change the font size of a chart title?
  5. What is the purpose of the color parameter?
  6. What is the purpose of the fontweight parameter?
  7. What is the difference between plt.title() and ax.set_title()?
  8. How can you control the spacing of axis labels?
  9. Why are meaningful axis labels important?
  10. Which parameter controls the title alignment?

Summary

In this lesson, you learned how to add titles and labels to Matplotlib charts. You explored the plt.title(), plt.xlabel(), and plt.ylabel() functions to describe chart information.

You also learned how to customize font size, colour, font weight, title position, and label spacing using different parameters. Finally, you explored how to add titles and labels using the object-oriented API.

Proper titles and labels make data visualizations more meaningful, readable, and professional.