W3docs

Matplotlib Labels

Learn how to add and customize axis labels, titles, legends, tick labels, and text annotations in Matplotlib with working Python examples.

Labels turn a raw chart into a readable story. This chapter covers every major label element in Matplotlib: axis labels, plot titles, legends, tick labels, and text annotations. For each element you will see the essential function, its most useful parameters, and practical examples you can run immediately.

Before you start, make sure Matplotlib is installed. See Matplotlib Getting Started for setup instructions.

Setting Axis Labels

The xlabel() and ylabel() functions attach descriptive text to the horizontal and vertical axes. Both accept the same parameters.

import matplotlib.pyplot as plt

height = [63, 64, 65, 66, 67, 68, 69, 70, 71, 72]
weight = [127, 130, 133, 136, 139, 142, 145, 148, 151, 154]

plt.scatter(height, weight)
plt.xlabel('Height (inches)')
plt.ylabel('Weight (pounds)')
plt.show()

Customizing Label Appearance

Both functions accept a fontsize argument (points) and any keyword from Matplotlib's Text class, such as color, fontweight, and fontstyle.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.xlabel('Time (seconds)', fontsize=13, color='steelblue', fontweight='bold')
plt.ylabel('Distance (meters)', fontsize=13, color='steelblue', fontweight='bold')
plt.show()

Adjusting Label Padding

Use the labelpad parameter to push a label further from the axis tick marks — useful when tick labels are long or rotated.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [1000, 2000, 3000, 4000, 5000]

plt.plot(x, y)
plt.xlabel('Quarter', labelpad=12)
plt.ylabel('Revenue ($)', labelpad=16)
plt.show()

Adding a Plot Title

The title() function adds a title centered above the plot by default.

import matplotlib.pyplot as plt

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
sales = [25000, 30000, 45000, 35000, 50000, 60000,
         70000, 80000, 90000, 100000, 110000, 120000]

plt.plot(months, sales)
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales ($)')
plt.show()

Title Positioning and Style

Pass loc ('left', 'center', 'right') to change horizontal alignment, and pad to control the gap between the title and the top of the plot.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [3, 7, 2, 9, 4]

plt.plot(x, y, marker='o')
plt.title('Sensor Readings', loc='left', pad=14,
          fontsize=15, fontweight='bold', color='darkslategray')
plt.show()

Figure-Level Title with suptitle()

When a figure contains multiple subplots, use suptitle() to add one title that spans all of them. Individual subplots can still have their own title().

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 3))

ax1.plot([1, 2, 3], [4, 5, 6])
ax1.set_title('Product A')

ax2.plot([1, 2, 3], [6, 5, 4])
ax2.set_title('Product B')

fig.suptitle('Q1 Sales Comparison', fontsize=14, fontweight='bold')
plt.tight_layout()
plt.show()

tight_layout() prevents the figure title from overlapping subplot content. See Matplotlib Subplots for a full treatment of multi-panel figures.

Customizing the Legend

A legend identifies the data series in your plot. Call legend() after plotting the series.

Basic Legend

Pass a label keyword to each plotting call, then call plt.legend() to render it.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

plt.plot(x, [2, 4, 6, 8, 10], label='Series A')
plt.plot(x, [1, 3, 5, 7, 9],  label='Series B')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Two Series')
plt.show()

Legend Location

Pass the loc parameter to place the legend precisely. Common values: 'upper left', 'upper right', 'lower left', 'lower right', 'center', or 'best' (Matplotlib picks the position with least overlap — the default).

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

plt.plot(x, [2, 4, 6, 8, 10], label='Revenue')
plt.plot(x, [1, 2, 3, 4, 5],  label='Costs')
plt.legend(loc='upper left')
plt.show()

Legend Outside the Axes

Use bbox_to_anchor together with loc to place the legend outside the plot area. Call tight_layout() or adjust subplots_adjust so the legend is not cropped.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
fig, ax = plt.subplots()

ax.plot(x, [1, 4, 9, 16],  label='Quadratic')
ax.plot(x, [1, 8, 27, 64], label='Cubic')
ax.legend(loc='upper left', bbox_to_anchor=(1, 1))
plt.tight_layout()
plt.show()

Styling the Legend

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

plt.plot(x, [2, 4, 6, 8, 10], label='Actual')
plt.plot(x, [1, 3, 5, 7, 9],  label='Forecast', linestyle='--')
plt.legend(
    title='Data',
    fontsize=11,
    title_fontsize=12,
    framealpha=0.9,
    edgecolor='gray',
)
plt.show()

framealpha controls the legend box opacity (0 = transparent, 1 = solid). title adds a header inside the legend box.

Customizing Tick Labels

Tick labels are the numbers or strings Matplotlib prints along each axis. Use xticks() and yticks() to override them.

Rotating Tick Labels

Long category names overlap by default. Rotate them with the rotation parameter.

import matplotlib.pyplot as plt

categories = ['January', 'February', 'March', 'April', 'May', 'June']
values = [12, 19, 14, 22, 18, 25]

plt.bar(categories, values)
plt.xticks(rotation=45, ha='right')
plt.ylabel('Units sold')
plt.title('Monthly Sales')
plt.tight_layout()
plt.show()

ha='right' aligns the right edge of each label with its tick mark, which looks cleaner after rotation.

Setting Custom Tick Values and Labels

Pass two lists to xticks(): the tick positions and the strings to display.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x))

ticks = [0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi]
labels = ['0', 'π/2', 'π', '3π/2', '2π']
plt.xticks(ticks, labels, fontsize=12)
plt.ylabel('sin(x)')
plt.title('Sine Wave with Custom Tick Labels')
plt.show()

Styling Tick Label Font

Both xticks() and yticks() accept font keyword arguments directly.

import matplotlib.pyplot as plt

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

plt.plot(x, y)
plt.xticks(fontsize=12, color='steelblue')
plt.yticks(fontsize=12, color='steelblue')
plt.show()

Adding Text Annotations

The text() function places a string at an arbitrary position inside the axes coordinate system.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 3, 6, 5]

plt.plot(x, y, marker='o')
plt.text(3, 3.2, 'dip here', fontsize=11, color='crimson')
plt.title('Text Annotation Example')
plt.show()

The first two arguments are the x and y coordinates in data units.

Annotating with an Arrow

annotate() draws a label plus an optional arrow pointing to a specific data point. It is the right tool when you want to highlight outliers or peaks.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [4, 7, 2, 9, 3]

plt.plot(x, y, marker='o')
plt.annotate(
    'Peak',
    xy=(4, 9),           # tip of the arrow (the data point)
    xytext=(3.2, 9.5),   # where the label sits
    arrowprops=dict(arrowstyle='->', color='black'),
    fontsize=12,
)
plt.title('Annotated Line Plot')
plt.show()

Object-Oriented API: Using Axes Methods

All of the functions above are convenience wrappers around the current active axes. When working with multiple subplots — or whenever you need precise control — use the Axes object's methods directly: ax.set_xlabel(), ax.set_ylabel(), ax.set_title(), ax.legend(), and ax.set_xticks().

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

months = ['Jan', 'Feb', 'Mar', 'Apr']
revenue = [12000, 15000, 13000, 18000]
costs   = [8000,  9000, 10000, 11000]

ax.plot(months, revenue, marker='o', label='Revenue')
ax.plot(months, costs,   marker='s', label='Costs', linestyle='--')

ax.set_xlabel('Month', fontsize=12)
ax.set_ylabel('Amount ($)', fontsize=12)
ax.set_title('Revenue vs Costs — Q1', fontsize=14)
ax.legend(loc='upper left')

plt.tight_layout()
plt.show()

Prefer the object-oriented style when your script creates more than one axes. The plt.* shortcuts route to whichever axes is currently active, which can produce hard-to-trace bugs in multi-subplot figures.

Quick Reference

GoalFunction (pyplot)Method (Axes)
X-axis labelplt.xlabel()ax.set_xlabel()
Y-axis labelplt.ylabel()ax.set_ylabel()
Plot titleplt.title()ax.set_title()
Figure titleplt.suptitle()fig.suptitle()
Legendplt.legend()ax.legend()
X tick labelsplt.xticks()ax.set_xticks() / ax.set_xticklabels()
Y tick labelsplt.yticks()ax.set_yticks() / ax.set_yticklabels()
Free textplt.text()ax.text()
Annotate + arrowplt.annotate()ax.annotate()
Was this page helpful?