To add an x-axis label in Matplotlib, call plt.xlabel("Label"), or ax.set_xlabel("Label") when you work with an Axes object (for example after plt.subplots()). Both accept text styling such as fontsize, color and fontweight, plus labelpad and loc for its position. This guide covers the matplotlib x-axis label from the basics to changing tick labels, showing every nth label, dates, and labels for subplots.
Tested with Python 3.12.5 and Matplotlib 3.11.2. The charts are real Matplotlib windows. Reference: matplotlib.pyplot.xlabel and Axes.set_xlabel.
Add x-axis and y-axis labels with plt.xlabel()
import matplotlib.pyplot as plt
years = [2019, 2020, 2021, 2022, 2023, 2024]
users = [1.2, 1.8, 2.9, 4.1, 5.0, 6.3]
plt.plot(years, users, marker="o")
plt.xlabel("Year") # x-axis label
plt.ylabel("Active users (millions)") # y-axis label
plt.title("App growth")
plt.show()
plt.xlabel() and plt.ylabel().plt.xlabel() vs ax.set_xlabel()
pyplot functions work on the current axes; Axes methods work on the axes you name. The names differ, and mixing them up is a common error:
| pyplot (current axes) | Axes object |
|---|---|
plt.xlabel() | ax.set_xlabel() |
plt.ylabel() | ax.set_ylabel() |
plt.title() | ax.set_title() |
plt.xticks() | ax.set_xticks() |
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.xlabel("Time") # pyplot name used on an Axes object
Result:
Traceback (most recent call last):
File "C:\pyguides\xlabel_error.py", line 5, in <module>
ax.xlabel("Time") # pyplot name used on an Axes object
^^^^^^^^^
AttributeError: 'Axes' object has no attribute 'xlabel'. Did you mean: '_label'?
ax.xlabel() does not exist; use ax.set_xlabel().Change the x-axis label font size, color and padding
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(["North", "South", "East", "West"], [42, 35, 51, 28], color="tab:cyan")
ax.set_xlabel("Sales region", fontsize=14, fontweight="bold", color="darkblue", labelpad=12)
ax.set_ylabel("Orders", fontsize=12, style="italic")
plt.tight_layout()
plt.show()
fontsize, fontweight, color and labelpad on set_xlabel().You can read the label back, and calling set_xlabel() again replaces the text while keeping its style:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([10, 20, 30], [1, 4, 9])
ax.set_xlabel("Distance (km)", fontsize=13)
label = ax.xaxis.label # the Text object behind the label
print("text: ", ax.get_xlabel())
print("fontsize: ", label.get_fontsize())
print("position: ", ax.xaxis.get_label_position())
ax.set_xlabel("Distance (miles)") # calling it again replaces the text
print("new text: ", ax.get_xlabel())
print("fontsize: ", ax.xaxis.label.get_fontsize(), "(kept)")
Output:
text: Distance (km)
fontsize: 13.0
position: bottom
new text: Distance (miles)
fontsize: 13.0 (kept)
To change the size of every axis label at once, set plt.rcParams["axes.labelsize"]. More font options are in Matplotlib title font size.
Change the x-axis label position
loc aligns the label to the left, centre or right of the axis. To put it above the plot, move the label position to the top:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(10, 3.4))
for ax in axes:
ax.plot([0, 1, 2, 3], [1, 3, 2, 4])
axes[0].set_xlabel("loc='left'", loc="left") # left / center / right
axes[1].set_xlabel("loc='right'", loc="right")
axes[2].set_xlabel("label on top")
axes[2].xaxis.set_label_position("top") # move the label above the plot
axes[2].xaxis.tick_top() # and the tick labels too
plt.tight_layout()
plt.show()
loc="left", loc="right" and a label on top.For exact placement, use axes coordinates: ax.xaxis.set_label_coords(0.5, -0.15).
Change the x-axis tick labels
The label is the axis title; the tick labels are the values along the axis. Replace them with set_xticks() and its labels argument:
import matplotlib.pyplot as plt
quarters = [1, 2, 3, 4]
revenue = [120, 135, 160, 190]
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(quarters, revenue, marker="o")
ax.set_xticks(quarters, labels=["Q1 2025", "Q2 2025", "Q3 2025", "Q4 2025"]) # custom tick labels
ax.set_xlabel("Quarter")
ax.set_ylabel("Revenue (k$)")
plt.tight_layout()
plt.show()
ax.set_xticks(positions, labels=...).Long tick labels are easier to read when rotated: see rotate tick labels in Matplotlib.
Show every nth x-axis label
With many points, Matplotlib may crowd the axis or pick awkward steps. MultipleLocator(n) puts a tick and label every n units:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator
days = np.arange(1, 101)
visits = 200 + 40 * np.sin(days / 8) + days
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(days, visits)
ax.xaxis.set_major_locator(MultipleLocator(10)) # a label every 10 days
ax.set_xlabel("Day")
ax.set_ylabel("Visits")
plt.tight_layout()
plt.show()
For category labels (strings), keep every nth one with ax.set_xticks(x[::10]).
Date labels on the x-axis
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
dates = pd.date_range("2025-01-01", periods=12, freq="MS")
sales = [210, 190, 230, 260, 250, 300, 320, 310, 280, 270, 330, 360]
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(dates, sales, marker="o")
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y")) # Jan 2025, Feb 2025, ...
ax.set_xlabel("Month")
fig.autofmt_xdate() # slant the date labels so they fit
plt.show()
DateFormatter("%b %Y") and fig.autofmt_xdate().X-axis labels for subplots
One label for all subplots
With shared axes, repeat labels waste space. fig.supxlabel() (Matplotlib 3.4+) adds one centred label for the whole figure:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, axes = plt.subplots(2, 2, figsize=(8, 5.5), sharex=True, sharey=True)
for i, ax in enumerate(axes.flat, start=1):
ax.plot(x, np.sin(x * i / 2))
ax.set_title(f"Sensor {i}")
fig.supxlabel("Time (seconds)") # one x-axis label for the whole figure
fig.supylabel("Amplitude")
plt.tight_layout()
plt.show()
A different label for each subplot
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.6))
ax1.bar(["A", "B", "C"], [5, 3, 7])
ax1.set_xlabel("Product") # each subplot has its own label
ax2.plot([1, 2, 3, 4], [10, 12, 9, 14])
ax2.set_xlabel("Week", color="tab:red")
plt.tight_layout()
plt.show()
set_xlabel().For more on shared axes, see share axes and axis labels in Matplotlib.
More Matplotlib axis tutorials:
- Rotate tick labels in Matplotlib
- Share axes and axis labels between subplots
- Set the axis range in Matplotlib
- Stop labels overlapping with tight_layout()
Frequently asked questions
How do I label the x-axis in Matplotlib?
Call plt.xlabel("Label") before plt.show(), or ax.set_xlabel("Label") on an Axes object.
What is the difference between plt.xlabel and ax.set_xlabel?
plt.xlabel() labels the current axes; ax.set_xlabel() labels a specific axes. Axes objects have no xlabel() method, so ax.xlabel() raises AttributeError.
How do I change the x-axis label font size?
Pass fontsize: plt.xlabel("Year", fontsize=14). For all labels, set plt.rcParams["axes.labelsize"].
How do I move the x-axis label?
Use loc="left" or "right", labelpad for distance, ax.xaxis.set_label_position("top") to put it on top, or ax.xaxis.set_label_coords(x, y).
How do I show every 10th label on the x-axis?
Use ax.xaxis.set_major_locator(MultipleLocator(10)) for numbers, or ax.set_xticks(x[::10]) for categories.
How do I add one x-axis label for all subplots?
fig.supxlabel("Label") adds a single label centred under all subplots.
Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn