Horizontal axis labels in Matplotlib
2021-01-09 | updated 2021-02-22
This is how to change the orientation of axis labels in a Matplotlib plot.
In a default Matplotlib plot, the tick labels for both the x- and y-axes are horizontal, but the axis label for the y-axis is vertical:
import numpy as np
rng = np.random.default_rng()
x = np.linspace(0, 9, 10)
y = rng.random(10) + 0.5
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid")
fig, ax = plt.subplots(figsize=(3, 2))
ax.scatter(x, y)
ax.set(xlabel="Predictor", ylabel="Response")
To make the y-axis label horizontal, which is easier to
read, pass in these
matplotlib.text.Text
properties as additional
parameters:
fig, ax = plt.subplots(figsize=(3, 2))
ax.scatter(x, y)
ax.set_xlabel("Predictor")
ax.set_ylabel(
"Response",
rotation="horizontal",
horizontalalignment="right",
verticalalignment="center_baseline",
)
Note that you might have to tweak the alignment parameters until it looks alright.
For a slightly more realistic example, this is what I needed this for in the first place: plotting my change in weight over the last year:
dates = np.arange("2020-03", "2020-11", dtype="datetime64[D]")
weights = (
2 * np.sin(np.linspace(0, 2 * np.pi, len(dates)))
+ rng.random(len(dates))
)
import matplotlib.dates as mdates
dtloc = mdates.AutoDateLocator()
dtfmt = mdates.ConciseDateFormatter(dtloc)
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(dates, weights)
ax.set_ylabel(
"Change\nin weight\n(%)",
rotation="horizontal",
horizontalalignment="right", # label relative to axis
multialignment="center", # lines within label
verticalalignment="center_baseline",
linespacing=1.5,
)
ax.xaxis.set_major_locator(dtloc)
ax.xaxis.set_major_formatter(dtfmt)
# Fix bounding box before saving to file.
fig.tight_layout()
Note also the use of
matplotlib.dates.ConciseDateFormatter
in the above to
improve the tick labels for the x axis.