放置文本框#

当用文本框装饰坐标轴时,两个有用的技巧是将文本放置在坐标轴坐标中(请参阅转换教程),这样文本就不会随着 x 或 y 限制的变化而移动。您还可以使用 text 的属性用实例bbox包围文本 ——关键字参数采用带有 Patch 属性键的字典。Patchbbox

放置文本框
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(19680801)

fig, ax = plt.subplots()
x = 30*np.random.randn(10000)
mu = x.mean()
median = np.median(x)
sigma = x.std()
textstr = '\n'.join((
    r'$\mu=%.2f$' % (mu, ),
    r'$\mathrm{median}=%.2f$' % (median, ),
    r'$\sigma=%.2f$' % (sigma, )))

ax.hist(x, 50)
# these are matplotlib.patch.Patch properties
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)

# place a text box in upper left in axes coords
ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
        verticalalignment='top', bbox=props)

plt.show()

由 Sphinx-Gallery 生成的画廊