Axis labels turn plotted values into named quantities that a reader can interpret without guessing the measure or unit. In Matplotlib, the labels belong to the Axes object that owns the x and y coordinate system, so the same calls work in scripts, notebooks, and subplot layouts.
Use set_xlabel() for the horizontal axis and set_ylabel() for the vertical axis after the data has been plotted on the target Axes. The label text can include units, and keyword arguments such as labelpad or fontsize pass through to the underlying Text object when spacing or styling needs adjustment.
A saved image and the get_xlabel() or get_ylabel() return values give two separate checks. The Axes stores the intended strings, and the exported figure leaves enough room for those labels to be readable.
Steps to set Matplotlib axis labels:
- Save the plotting script as axis_labels.py.
- axis_labels.py
from pathlib import Path import matplotlib.pyplot as plt months = ["Jan", "Feb", "Mar", "Apr"] revenue = [42, 48, 52, 57] fig, ax = plt.subplots(layout="constrained") ax.plot(months, revenue, marker="o") ax.set_xlabel("Month", labelpad=8) ax.set_ylabel("Revenue (USD thousands)", labelpad=8) output = Path("axis-set-label.png") fig.savefig(output, dpi=150) print(f"x label: {ax.get_xlabel()}") print(f"y label: {ax.get_ylabel()}") print(f"saved: {output}")
labelpad sets the spacing in points between the axis label and the tick labels. Omit it when the default spacing is enough.
Related: How to save a Matplotlib figure
- Run the script from the directory where the PNG should be written.
$ python axis_labels.py x label: Month y label: Revenue (USD thousands) saved: axis-set-label.png
- Use a newline only when a long label needs to wrap inside the figure.
ax.set_ylabel("Revenue\n(USD thousands)")
Matplotlib renders \n as a line break inside the label text.
- Open axis-set-label.png and check the exported labels.
The x-axis should read Month below the tick labels, and the y-axis should read Revenue (USD thousands) beside the vertical axis. If a long label is clipped in a real figure, keep layout="constrained" or adjust layout before exporting.
Related: How to fix overlapping labels in Matplotlib
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.