Text below a figure with matplotlib

Question:

I managed to add text on the figure with

        fg_ax.text(
            0.05,
            0.1,
            f"n = {len(df)}",
        )

fg_ax being my matplotlib.axes object

But I want it below the figure. Because my y coordinates go from 0 to 1, I figured after reading the documentation that doing something like this would put it below:

        fg_ax.text(
            0.05,
            -0.5,
            f"n = {len(df)}",
        )

But there is nothing that appears anymore, as if I was writing "outside" what is displayed.

I tried plt.show() and fg_ax.figure.savefig. None works.

Minimal reproducible example:

import numpy as np
import matplotlib.pyplot as plt


N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N)) ** 2  # 0 to 15 point radii

_, fg_ax = plt.subplots()
fg_ax.scatter(x, y, s=area, c=colors, alpha=0.5)
fg_ax.text(
    0.05,
    -0.5,
    f"n = qsdfqsdf",
)
plt.show()

Answers:

Based on this answer, I’ve changed your code to the following:

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N)) ** 2  # 0 to 15 point radii

fig, fg_ax = plt.subplots()
fg_ax.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.figtext(
    0.2, 0.01, f"n = qsdfqsdf", wrap=True, horizontalalignment='center', fontsize=10
)
fig.subplots_adjust(bottom=0.3)
plt.savefig("image.pdf", format="pdf", bbox_inches="tight")
plt.show()

enter image description here

Answered By: blunova
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.