我想知道图形分数坐标中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'
)
Run Code Online (Sandbox Code Playgroud)
patch = ann.get_bbox_patch()
print(patch.get_extents())
Run Code Online (Sandbox Code Playgroud)
给出:
[[-0.33 -0.33]
[ 1.33 1.33]]
c = patch.get_transform().transform(patch.get_extents())
print(c)
Run Code Online (Sandbox Code Playgroud)
给出:
[[-211.2 -158.4]
[ 851.2 638.4]]
Run Code Online (Sandbox Code Playgroud)
大概是显示坐标,但它们与我想要属性的标签的位置和大小不对应。
在绘制图形之前,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)
Run Code Online (Sandbox Code Playgroud)
由于这些是显示单位中框的坐标,因此需要将它们转换为图形单位
tcbox = fig.transFigure.inverted().transform(box)
print tcbox
#prints [[ 0.411875 0.39919185]
# [ 0.50023438 0.44460851]]
# The format is
# [[ left bottom]
# [ right top ]]
Run Code Online (Sandbox Code Playgroud)
这将以文本周围的矩形的图形单位(从0到1)返回边界框。
相反,如果需要轴坐标,它将是
ax.transAxes.inverted().transform(box)
Run Code Online (Sandbox Code Playgroud)
或者如果需要数据坐标,
ax.transData.inverted().transform(box)
Run Code Online (Sandbox Code Playgroud)
get_window_extent()
方法matplotlib.text.Text
并提供注释对象作为参数。使用
box = matplotlib.text.Text.get_window_extent(ann)
print box
# prints Bbox(x0=268.0, y0=196.012085684, x1=315.75, y1=209.012085684)
Run Code Online (Sandbox Code Playgroud)
可以按照上述步骤进行操作,以图形为单位获取方框。
归档时间: |
|
查看次数: |
1948 次 |
最近记录: |