简体   繁体   中英

Text below a figure with matplotlib

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()

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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM