使用 ax.text、matplotlib 相对于轴定位字体

bax*_*axx 1 python plot axis matplotlib

我不确定如何使用 matplotlib 相对于轴对象正确定位字体。

例子:

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10, 4), dpi=100)
x = [1, 2]
y = [3, 4]

y_loc = 4.1
x_loc = 0.95
fs = 12
ax = axes[0]
ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 1", fontsize=fs)

ax = axes[1]
ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 2", fontsize=fs)

ax = axes[2]
_ = ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 3", fontsize=fs)
Run Code Online (Sandbox Code Playgroud)

这使:

在此处输入图片说明

值的使用:

y_loc = 4.1
x_loc = 0.95
Run Code Online (Sandbox Code Playgroud)

让我觉得应该有更好的方法来解决这个问题。

注意 - 我想ax.text在这里使用,而不是title,问题主要是关于如何最好地相对于子图中的特定轴定位文本。理想情况下,如果它只是相对于特定轴,它也会扩展到网格图。

Joh*_*anC 6

默认情况下,ax.text使用“数据坐标”,即 x 和 y 显示在轴的刻度上。要相对于轴定义的矩形绘图,请使用transform=ax.transAxes。这里0,0将是左下角1,1的点和右上角的点。(这种坐标在定位图例时也非常有用。)

from matplotlib import pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10, 4), dpi=100)

for ind, ax in enumerate(axes):
    ax.plot(np.random.randint(0, 10, 2), np.random.randint(0, 10, 2))
    ax.text(x=0, y=1.05, s=f"Plot {ind+1}", fontsize=12, transform=ax.transAxes)
plt.show()
Run Code Online (Sandbox Code Playgroud)

示例图