Mathew K Analytics

Lesson 10 · Data visualisation in python

How to Customize Titles, Labels, and Legends in Matplotlib for Clearer Data Visualization

In this lesson, you will learn how to make your plots easier to understand by customizing titles, axis labels, and legends using Matplotlib. These skills…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Welcome to Customizing Titles, Labels, and Legends in Matplotlib!#

In this lesson, you will learn how to make your plots easier to understand by customizing titles, axis labels, and legends using Matplotlib.

These skills help you turn plain charts into clear, professional graphics.

Let us get started!

import warnings
warnings.filterwarnings("ignore")

# Import the main libraries for plotting and data handling.
import matplotlib.pyplot as plt
import pandas as pd

What Are Titles, Labels, and Legends For?#

Titles tell viewers what your whole plot is about. Axis labels explain what the numbers or categories on each axis mean. Legends help people match colors or lines to their meaning.

For helpful graphs, these are extremely important!

# Data setup
# Let us use a real-world dataset of monthly airline passengers for practice.
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
data = pd.read_csv(url)
print("Data shape:", data.shape)
print(data.head())
Data shape: (144, 2)
     Month  Passengers
0  1949-01         112
1  1949-02         118
2  1949-03         132
3  1949-04         129
4  1949-05         121
# Plotting our time series
# Let us make a simple line plot of the data to start.
plt.figure(figsize=(10, 4))
plt.plot(data["Month"], data["Passengers"])
plt.show()
No description has been provided for this image

Adding a Title#

Titles tell the story of your plot. Let us add one so people know what this chart shows.

# Adding a plot title
plt.figure(figsize=(10, 4))
plt.plot(data["Month"], data["Passengers"])
plt.title("Monthly Airline Passengers (1949-1960)")
plt.show()
No description has been provided for this image

Labeling Your Axes#

Axis labels explain what each axis measures. This is key for understanding numbers and comparisons.

Let us give our X and Y axes clear labels.

# Adding axis labels
plt.figure(figsize=(10, 4))
plt.plot(data["Month"], data["Passengers"])
plt.title("Monthly Airline Passengers (1949-1960)")
plt.xlabel("Month")
plt.ylabel("Number of Passengers")
plt.show()
No description has been provided for this image

Customizing How Titles and Labels Look#

Matplotlib lets you change the font size, color, and style for titles and labels. Try making the title blue and a little larger for more impact.

# Customizing title style
plt.figure(figsize=(10, 4))
plt.plot(data["Month"], data["Passengers"])
plt.title("Monthly Airline Passengers (1949-1960)", fontsize=16, color="blue", fontweight="bold")
plt.xlabel("Month", fontsize=12, color="darkgreen")
plt.ylabel("Number of Passengers", fontsize=12, color="purple")
plt.show()
No description has been provided for this image

Using Legends#

Legends link colors or lines to their meanings when you have more than one dataset or line in a plot. Good legends prevent confusion for your audience.

# Adding a second line and a legend
# Let us create a simple moving average to compare.
data["Rolling_Avg"] = data["Passengers"].rolling(window=12).mean()
plt.figure(figsize=(10, 4))
plt.plot(data["Month"], data["Passengers"], label="Monthly Passengers")
plt.plot(data["Month"], data["Rolling_Avg"], label="12-Month Average", linestyle="--")
plt.title("Airline Passengers and 12-Month Average")
plt.xlabel("Month")
plt.ylabel("Number of Passengers")
plt.legend()
plt.show()
No description has been provided for this image
# Customizing the legend
plt.figure(figsize=(10, 4))
plt.plot(data["Month"], data["Passengers"], label="Monthly Passengers")
plt.plot(data["Month"], data["Rolling_Avg"], label="12-Month Average", linestyle="--")
plt.title("Airline Passengers and 12-Month Average")
plt.xlabel("Month")
plt.ylabel("Number of Passengers")
plt.legend(loc="upper left", fontsize=12, title="Legend", title_fontsize=13, frameon=True, facecolor="whitesmoke")
plt.show()
No description has been provided for this image

More Label and Legend Tricks#

Matplotlib gives you even more ways to customize, like rotating labels, wrapping text, or hiding the legend. Let us see how to rotate labels for long text.

# Rotating x-axis labels to prevent overlap
plt.figure(figsize=(10, 4))
plt.plot(data["Month"], data["Passengers"])
plt.title("Monthly Airline Passengers (1949-1960)")
plt.xlabel("Month")
plt.ylabel("Number of Passengers")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
No description has been provided for this image
# Hiding the legend if you want a simple plot
plt.figure(figsize=(10, 4))
plt.plot(data["Month"], data["Passengers"], label="Monthly Passengers")
plt.title("Monthly Airline Passengers (1949-1960)")
plt.xlabel("Month")
plt.ylabel("Number of Passengers")
# No plt.legend() this time
plt.show()
No description has been provided for this image

Mini-Project Part 1: Custom Airline Analysis Plot#

Let us pull it together! Make your own plot summarizing airline passenger trends. Try using a custom title, labels, and a styled legend. Pick your own colors, font sizes, or legend location.

# Your turn: customize a plot
plt.figure(figsize=(12, 6))
plt.plot(data["Month"], data["Passengers"], color="orange", label="Passengers")
plt.plot(data["Month"], data["Rolling_Avg"], color="navy", linestyle=":", linewidth=3, label="12-Month Mean")
plt.title("Flight Trends: Passengers 1949-1960", fontsize=20, color="darkred", fontweight="bold")
plt.xlabel("Month", fontsize=13, color="teal")
plt.ylabel("Passengers", fontsize=13, color="olive")
plt.legend(loc="best", fontsize=12, frameon=True, facecolor="#f7f7f7")
plt.xticks(rotation=60)
plt.tight_layout()
plt.show()
No description has been provided for this image

Mini-Project Part 2: Show Travel Growth#

Highlight key points using annotation. You can add text to point out important dates or patterns in your plot!

# Annotate a special event: big growth in 1958
plt.figure(figsize=(12, 6))
plt.plot(data["Month"], data["Passengers"], color="dodgerblue", label="Passengers")
plt.plot(data["Month"], data["Rolling_Avg"], color="firebrick", linestyle="--", label="12-Month Mean")
plt.title("Airline Passenger Surge Highlight", fontsize=18, color="midnightblue")
plt.xlabel("Month", fontsize=12)
plt.ylabel("Passengers", fontsize=12)
plt.legend(loc="upper left")
plt.xticks(rotation=45)
plt.tight_layout()
# Annotate the peak in July 1958
plt.annotate("Rapid Growth", xy=("1958-07", 360), xytext=("1957-12", 420),
             arrowprops=dict(facecolor="black", shrink=0.05, width=2),
             fontsize=13, color="purple")
plt.show()
No description has been provided for this image

Troubleshooting: My Title or Labels Do Not Show Up#

If your chart is missing titles, labels, or legends:

  • Check that you spelled the commands correctly (title, xlabel, ylabel, legend).
  • Is plt.show() at the end? Without it, your changes may not appear.
  • Are you running the newest version of matplotlib?

Small errors can hide important details. Practice helps!

# Tip: Add grid lines for readability
plt.figure(figsize=(10, 4))
plt.plot(data["Month"], data["Passengers"])
plt.title("Monthly Airline Passengers (1949-1960)")
plt.xlabel("Month")
plt.ylabel("Number of Passengers")
plt.grid(True, color="lightgray", linestyle=":", linewidth=1)
plt.show()
No description has been provided for this image

Challenge Time!#

  1. Make a line plot of 'Passengers' for the year 1953 only.
  2. Add a custom title, axis labels, and a colored legend.
  3. Bonus: Try annotating the highest passenger value in 1953.

Give it a try on your own and explore!

Recap: Customizing Titles, Labels, and Legends#

Titles, axis labels, and legends make your plots much easier to read. You learned how to:

  • Set and style plot titles
  • Label your axes
  • Add and customize legends
  • Adjust label angles and grid lines
  • Annotate plots to highlight key points

These tools help you share your data's story clearly. Keep practicing and try them out with your own datasets!

What Next? Share Your Plots!#

Well done! You are now ready to make Python plots that look professional and are easy to understand. Practice with more datasets and try your own color styles or layouts. If you enjoyed this lesson, like and subscribe on YouTube for more hands-on Python tutorials. See you in the next lesson!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.