繁体   English   中英

在图形坐标中获取 Matplotlib 注释标签的坐标

[英]Getting the coordinates of a Matplotlib annotation label in figure coordinates

我想知道图形分数坐标中 Matplotlib 图的文本注释的边界矩形的坐标。 但是,当我尝试访问与注释关联的补丁的“范围”时,无论文本标签的大小如何,我都会得到Bbox(x0=-0.33, y0=-0.33, x1=1.33, y1=1.33) 这些坐标似乎与IdentityTransform相关联,但不会转换为任何有意义的图形分数坐标。 如何以图形分数单位获取标签的坐标(理想情况下,左下角和右上角)?

例子:

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return 10 * np.sin(3*x)**4

x = np.linspace(0, 2*np.pi, 100)
y = f(x)

fig, ax = plt.subplots()
ax.plot(x,y)

xpt = 1.75
ypt = f(xpt)
xy = ax.transData.transform([xpt, ypt])
xy = fig.transFigure.inverted().transform(xy)

xytext = xy + [0.1, -0.1]
rdx, rdy = 0, 1
ann = ax.annotate('A point', xy=xy, xycoords='figure fraction',
             xytext=xytext, textcoords='figure fraction',
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3",
                             relpos=(rdx, rdy)),
             bbox=dict(fc='gray', edgecolor='k', alpha=0.5),
             ha='left', va='top'
            )

在此处输入图片说明

patch = ann.get_bbox_patch()
print(patch.get_extents())

给出:

[[-0.33 -0.33]
 [ 1.33  1.33]]

c = patch.get_transform().transform(patch.get_extents())
print(c)

给出:

[[-211.2 -158.4]
 [ 851.2  638.4]]

大概这些是显示坐标,但它们与我想要属性的标签的位置和大小不对应。

在绘制图形之前, text对象的边界框仅包含该框相对于内部文本的坐标。

因此需要先绘制图形,然后访问边界框。

fig.canvas.draw() 
patch = ann.get_bbox_patch()
box  = patch.get_extents()
print box
#prints: Bbox(x0=263.6, y0=191.612085684, x1=320.15, y1=213.412085684)

由于这些是显示单位中框的坐标,因此需要将它们转换为图形单位

tcbox = fig.transFigure.inverted().transform(box)
print tcbox
#prints [[ 0.411875    0.39919185]
#        [ 0.50023438  0.44460851]]

# The format is 
#        [[ left    bottom]
#         [ right   top   ]]

这将返回文本周围矩形的图形单位(范围从 0 到 1)的边界框。

相反,如果需要轴坐标,那就是

ax.transAxes.inverted().transform(box)

或者如果需要数据坐标,

ax.transData.inverted().transform(box)


相反,如果文本本身的边界框是需要的,则可以使用matplotlib.text.Textget_window_extent()方法并提供注释对象作为参数。 使用

box = matplotlib.text.Text.get_window_extent(ann) print box # prints Bbox(x0=268.0, y0=196.012085684, x1=315.75, y1=209.012085684)

可以按照上述步骤获得图形单位的框。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM