智能自动定位文本框的情节

时间:2015-03-10 15:43:35

标签: python matplotlib

我按照Joe Kington给出in this answer的方法,使用matplotlib.offsetbox.AnchoredText()模块将一个文本框放在情节的一角。

如果我知道我想要放置文本框的位置,这可以很好地工作,但是如果我希望框定位自己以便重叠在同一图中绘制的内容的最小可能部分

这需要尽可能普遍地工作,因此我假设我不知道绘制的内容将是什么以及它在图中的位置。

我查看了documentation,但似乎没有smart选项可用。位置代码为:

'upper right'  : 1,
'upper left'   : 2,
'lower left'   : 3,
'lower right'  : 4,
'right'        : 5,
'center left'  : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center'       : 10,

例如,在这种情况下(MWE如下):

enter image description here

更好的位置是左上角(或下方),但由于我通过loc=1手动修复了位置,因此文本框与绘制的内容重叠。

有没有办法检测图中哪里有更多可用的空白空间并将盒子放在那里?


MWE:

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([0, 5, 0, 1])

import random
pointx = [3. + random.random() for i in xrange(1000)]
pointy = [random.random() for i in xrange(1000)]
plt.scatter(pointx , pointy)

# 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()

1 个答案:

答案 0 :(得分:1)

超过3年后,这是解决方案:代替offsetbox只需使用plt.legend()并利用默认情况下将文本框放置在“最佳”位置的功能。

enter image description here

import matplotlib.pyplot as plt

# 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([0, 5, 0, 1])

import random
pointx = [3. + random.random() for i in xrange(1000)]
pointy = [random.random() for i in xrange(1000)]
plt.scatter(pointx , pointy)

# 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

# Create an empty plot with the required text.
plt.plot([], label=text)
# Remove the handle from the legend box.
plt.legend(handlelength=0)

plt.show()
相关问题