快速而肮脏的方法是使用右对齐和上对齐的文本,并将其放置在距轴角的固定偏移处:
import matplotlib.pyplot as plt
# Define some names and variables to go in the text box.
xn, yn, cod = 'r', 'p', 'abc'
prec = 2
ccl = [546.35642, 6785.35416]
ect = [12.5235, 13.643241]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.axis([-1, 10, -1, 1])
# Generate text to write.
text1 = "${}_{{t}} = {:.{p}f} \pm {:.{p}f}\; {c}$".format(xn, ccl[0],
ect[0], c=cod, p=prec)
text2 = "${}_{{t}} = {:.{p}f} \pm {:.{p}f}\; {c}$".format(yn, ccl[1],
ect[1], c=cod, p=prec)
text = text1 + '\n' + text2
ax.annotate(text, xy=(1, 1), xytext=(-15, -15), fontsize=10,
xycoords='axes fraction', textcoords='offset points',
bbox=dict(facecolor='white', alpha=0.8),
horizontalalignment='right', verticalalignment='top')
plt.show()
![enter image description here](https://i.stack.imgur.com/Kzrcs.png)
因为我们已经指定了顶部和右侧对齐,所以它适用于您的两种边缘情况:
![enter image description here](https://i.stack.imgur.com/ntJ7U.png)
![enter image description here](https://i.stack.imgur.com/GAtoU.png)
这样做的缺点是文本是右对齐的。理想情况下,您希望文本对齐方式与框对齐方式分开。这matplotlib.offsetbox
模块有许多方法来处理此类事情。
如果您想模仿图例框(直至位置代码),请查看matplotlib.offsetbox.AnchoredText
。 (请注意,您可以通过以下方式调整填充等pad
and borderpad
夸格斯:http://matplotlib.org/api/offsetbox_api.html#matplotlib.offsetbox.AnchoredOffsetbox )
import matplotlib.pyplot as plt
import matplotlib.offsetbox as offsetbox
# Define some names and variables to go in the text box.
xn, yn, cod = 'r', 'p', 'abc'
prec = 5
ccl = [546.35642, 6785.35416]
ect = [12.5235, 13.643241]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.axis([-1, 10, -1, 1])
# Generate text to write.
text1 = "${}_{{t}} = {:.{p}f} \pm {:.{p}f}\; {c}$".format(xn, ccl[0],
ect[0], c=cod, p=prec)
text2 = "${}_{{t}} = {:.{p}f} \pm {:.{p}f}\; {c}$".format(yn, ccl[1],
ect[1], c=cod, p=prec)
text = text1 + '\n' + text2
ob = offsetbox.AnchoredText(text, loc=1)
ax.add_artist(ob)
plt.show()
![enter image description here](https://i.stack.imgur.com/akhVn.png)
这样做的一个缺点是调整结果的字体和框参数有点违反直觉。AnchoredText
接受字体参数字典作为prop
夸格。初始化后可以通过以下方式调整该框patch
属性。举个简单的例子:
ob = offsetbox.AnchoredText(text, loc=1,
prop=dict(color='white', size=20))
ob.patch.set(boxstyle='round', color='blue', alpha=0.5)
ax.add_artist(ob)
![enter image description here](https://i.stack.imgur.com/5ZpAM.png)