Matplotlib Axis Labels: Font Size, Padding, Position, and Rotation

Add x and y axis labels in Matplotlib and control their font size, spacing, position, and rotation, including shared labels for subplots.

To label the axes in Matplotlib, call ax.set_xlabel("text") and ax.set_ylabel("text"), or plt.xlabel() and plt.ylabel() with the pyplot interface. fontsize sets the size, labelpad the gap between the label and the tick labels, and loc where the label sits along the axis.

Quick Example

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(73)
minutes = np.arange(0, 481, 5)
co2 = 430 + 780 * (1 - np.exp(-minutes / 190)) - 260 * np.exp(-((minutes - 260) / 35) ** 2)
co2 += rng.normal(0, 14, minutes.size)

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
ax.plot(minutes, co2, color="#0e7490", linewidth=2)
ax.set_title("Air quality in a meeting room")
ax.set_xlabel("Minutes since 9:00", fontsize=13, labelpad=10)
ax.set_ylabel("CO$_2$ concentration (ppm)", fontsize=13, labelpad=10)
plt.show()

Matplotlib line chart of carbon dioxide in a meeting room with large, padded x and y axis labels and a subscript 2 in the y label

The $_2$ is Matplotlib's built-in math text, which draws the subscript without needing LaTeX installed. More examples are in LaTeX equations in Matplotlib labels. The code targets Matplotlib 3.10 and 3.11.

plt.xlabel or ax.set_xlabel?

You're using... x label y label
pyplot (plt.plot(...)) plt.xlabel("Time") plt.ylabel("Value")
An Axes (fig, ax = plt.subplots()) ax.set_xlabel("Time") ax.set_ylabel("Value")
One call for several properties ax.set(xlabel="Time", ylabel="Value")
A whole grid of subplots fig.supxlabel("Time") fig.supylabel("Value")

The pyplot functions label the current Axes and accept the same styling arguments. With more than one subplot, the ax methods make it clear which chart you're changing. ax.set() is compact but only takes the text.

Change the Font Size, Weight, and Color

Both setters accept Matplotlib text properties as keyword arguments.

styles = [
    ("fontsize=16", {"fontsize": 16}),
    ('fontweight="bold"', {"fontweight": "bold"}),
    ('color="#be123c"', {"color": "#be123c"}),
    ('fontstyle="italic",\nfontfamily="serif"', {"fontstyle": "italic", "fontfamily": "serif"}),
]
fig, axes = plt.subplots(1, 4, figsize=(11, 2.8), layout="constrained")
for ax, (title, kwargs) in zip(axes, styles):
    ax.plot(minutes, co2, color="#94a3b8")
    ax.set_title(title, fontsize=10)
    ax.set_xlabel("Minutes", **kwargs)
    ax.set_ylabel("CO$_2$ (ppm)", **kwargs)
plt.show()

Four Matplotlib charts showing axis labels at font size 16, in bold, in red, and in an italic serif font

To change every chart in a script, set the defaults once with rcParams:

plt.rcParams.update({
    "axes.labelsize": 13,       # default "medium"
    "axes.labelweight": "bold",  # default "normal"
    "axes.labelcolor": "#334155",
    "axes.labelpad": 8,          # default 4.0
})
plt.rcdefaults()  # undo, so the examples below use the defaults

Tick labels are styled separately, as covered in tick label font size and style.

Add Space Between a Label and the Axis

labelpad is the gap in points between the label and the tick labels. The default is 4.

fig, axes = plt.subplots(1, 3, figsize=(11, 2.9), layout="constrained")
for ax, pad in zip(axes, [0, 4, 25]):
    ax.bar(["Mon", "Tue", "Wed", "Thu"], [14, 22, 19, 27], color="#f59e0b")
    ax.set_title(f"labelpad={pad}" + (" (default)" if pad == 4 else ""))
    ax.set_xlabel("Day of week", labelpad=pad)
    ax.set_ylabel("Bookings", labelpad=pad)
plt.show()

Three Matplotlib bar charts comparing axis label spacing with labelpad of 0, 4, and 25 points

You can also change it after the fact with ax.xaxis.labelpad = 12.

Move a Label Along the Axis with loc

loc takes "left", "center", or "right" for the x label, and "bottom", "center", or "top" for the y label.

speed = np.linspace(20, 130, 60)
fuel = 3.2 + 0.00065 * (speed - 62) ** 2

fig, axes = plt.subplots(1, 3, figsize=(11, 3), layout="constrained")
for ax, (xloc, yloc) in zip(axes, [("left", "bottom"), ("center", "center"), ("right", "top")]):
    ax.plot(speed, fuel, color="#7c3aed", linewidth=2.5)
    ax.set_title(f'x: "{xloc}", y: "{yloc}"')
    ax.set_xlabel("Speed (km/h)", loc=xloc)
    ax.set_ylabel("L per 100 km", loc=yloc)
plt.show()

Three Matplotlib charts with axis labels placed at the start, center, and end of each axis

loc sets the position and alignment for you, so passing it together with ha, or with x (x label) or y (y label), raises a TypeError. The default for all charts is set by rcParams["xaxis.labellocation"] and rcParams["yaxis.labellocation"].

How Do I Make the Y-Axis Label Horizontal?

Pass rotation=0. The y label is rotated 90 degrees by default, and its alignment was chosen for that, so also set ha="right" and va="center" to keep the text clear of the tick labels.

years = np.arange(2016, 2027)
trees = np.array([120, 180, 260, 310, 420, 480, 610, 700, 790, 930, 1040])

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.bar(years, trees, color="#15803d")
ax.set_ylabel("Trees\nplanted", rotation=0, ha="right", va="center", labelpad=12)
ax.set_xlabel("Year")
ax.set_xticks(years[::2])
ax.spines[["top", "right"]].set_visible(False)
plt.show()

Matplotlib bar chart of trees planted per year with a horizontal two-line y-axis label centered to the left of the axis

A \n splits long labels onto two lines. For angled tick labels, which is the more common need on crowded x-axes, see rotating axis labels in Matplotlib.

Move Labels to the Top or Right

The label and the ticks move independently, so call both: tick_right() with set_label_position("right"), or tick_top() with set_label_position("top").

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.plot(years, trees, "o-", color="#15803d")
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
ax.set_ylabel("Trees planted")
ax.xaxis.tick_top()
ax.xaxis.set_label_position("top")
ax.set_xlabel("Year", labelpad=8)
plt.show()

Matplotlib line chart with the year label and ticks above the plot and the y label and ticks on the right side

If you want a second scale on the right, that's a dual y-axis chart.

One Shared Label for Multiple Subplots

fig.supxlabel() and fig.supylabel() write a single label for the whole figure. Pair them with sharex=True and sharey=True so one label really does describe every panel. Use layout="constrained" to reserve room for them.

rooms = ["Library", "Studio", "Lab", "Office", "Lounge", "Workshop"]
fig, axes = plt.subplots(2, 3, figsize=(9, 5), sharex=True, sharey=True, layout="constrained")
hour = np.arange(9, 18)
for ax, room in zip(axes.flat, rooms):
    temp = 19 + rng.uniform(0, 2) + rng.uniform(0.2, 0.5) * (hour - 9) + rng.normal(0, 0.25, hour.size)
    ax.plot(hour, temp, color="#c2410c")
    ax.set_title(room)
fig.supxlabel("Hour of day")
fig.supylabel("Temperature (°C)")
plt.show()

Six small temperature line charts for different rooms sharing one x label for hour of day and one y label for temperature

If you set labels on each subplot instead, ax.label_outer() hides the ones on inner panels of a grid.

Align Y Labels Across Subplots

A y label sits next to its tick labels, so panels with wide numbers push their labels further out. fig.align_ylabels() lines them up. Pass a list of Axes to align one column; fig.align_xlabels() does the same for x labels.

fig, axes = plt.subplots(2, 2, figsize=(11, 4.6), layout="constrained")
for column, align in zip(axes.T, [False, True]):
    column[0].plot(hour, hour * 125000, color="#334155")
    column[0].ticklabel_format(axis="y", style="plain")
    column[0].set_ylabel("Revenue")
    column[1].plot(hour, hour / 4, color="#334155")
    column[1].set_ylabel("Staff")
    column[0].set_title("fig.align_ylabels()" if align else "Default")
    if align:
        fig.align_ylabels(column)
plt.show()

Two columns of stacked charts showing misaligned Revenue and Staff y labels by default and aligned labels after calling align_ylabels

Practical Tips

  • Put units in the label, such as "Speed (km/h)", so the numbers can be read without the surrounding text.
  • If a label is cut off in a saved file, use layout="constrained" or savefig(..., bbox_inches="tight"). See saving figures in Matplotlib.
  • ax.set_xlabel("") removes a label, which is handy for date axes that explain themselves. To remove ticks too, see hiding axis ticks and labels.

Similar Topics