将文本框固定在角落并正确对齐

2023-11-27

我正在尝试模仿legend中的方法matplotlib.pyplot哪里可以使用loc='lower right'定位图例框固定并正确对齐无论轴和盒子的内容如何。

Using text已经出来了,因为这需要手动输入坐标,而我正在寻找自动的东西。

我尝试过使用annotate它让我成功了一半,但仍然无法正常工作。

这是我到目前为止所拥有的:

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)
plt.xlim(-1., 10.)
plt.ylim(-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=(0.75, 0.9), xycoords='axes fraction', fontsize=10,
    bbox=dict(facecolor='white', alpha=0.8),
    horizontalalignment='left', verticalalignment='bottom')

plt.savefig('annotate_test.png', dpi=150)

结果是:

enter image description here

这将正确缩放以更改轴限制,但问题是: 1-如果轴设置为,它将失败ax.set_aspect('equal'):

enter image description here

2-如果文本太长就会失败(这里我设置prec=5在上面的 MWE 中):

enter image description here

我怎么知道matplotlib定位文本框始终位于右上角并正确对齐所以它不会落在图像之外(即:什么loc确实在legend)?


快速而肮脏的方法是使用右对齐和上对齐的文本,并将其放置在距轴角的固定偏移处:

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

因为我们已经指定了顶部和右侧对齐,所以它适用于您的两种边缘情况:

enter image description here

enter image description here


这样做的缺点是文本是右对齐的。理想情况下,您希望文本对齐方式与框对齐方式分开。这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

这样做的一个缺点是调整结果的字体和框参数有点违反直觉。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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将文本框固定在角落并正确对齐 的相关文章

随机推荐