放置文本框

放置文本框#

在用文本框装饰轴时,两个有用的技巧是:将文本放置在轴坐标中(参见变换教程),这样文本不会随着 xy 限制的变化而移动。您还可以使用文本的 bbox 属性来围绕文本添加 Patch 实例——bbox 关键字参数接受字典,其键是 Patch 的属性。

import matplotlib.pyplot as plt
import numpy as np

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()
../../../_images/8f33840b7625bc7375a36162b3c7db5f76dff33c9240319e7a369427748d5a84.png