2016-12-21 159 views
1

我想知道圖形分數座標Matplotlib圖的文本註釋的邊界矩形的座標。但是,當我嘗試訪問與註釋關聯的修補程序的「範圍」時,無論文本標籤的大小如何,我都會得到Bbox(x0=-0.33, y0=-0.33, x1=1.33, y1=1.33)。這些座標似乎與IdentityTransform相關聯,但不會轉換爲任何有意義的數字分數座標。 如何獲得標註的座標(理想情況下,左下角和右上角)的圖形分數單位?獲取圖形座標Matplotlib註釋標籤的座標

實施例:

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' 
      ) 

enter image description here

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]] 

推測這些是顯示座標,但它們不對應於我想要的屬性的標籤的位置和大小。

回答

2

在繪製圖形之前,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) 

由於這些是在顯示單元的框的座標,它們需要被tranformed推測單元

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)的邊界框圍繞文本的矩形。


如果不是文本本身是什麼beeing問一個可以使用的 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) 

可以像上面那樣進行操作以獲得圖中單位的框。

+0

謝謝 - 雖然我有一個問題:我只能在'plt.show()'之後重現正確的bbox座標:它不足以調用'fig.canvas.draw()'...是這個後端問題?我在OS X上。 – xnx

+0

因爲我沒有任何關於Mac的經驗,所以我只能說這個方法在Windows下的matplotlib 1.5中有後端'agg','TkAgg'和'Qt4Agg'。 – ImportanceOfBeingErnest

+0

是的 - 這是Mac OS X後端的錯誤。用'agg'很好地工作。謝謝你的幫助。 – xnx