2014-01-09 58 views
2

我想要定位一些額外的註釋,以便與matplotlib圖中的軸標籤文本對齊。該位置是如何計算的,作爲刻度線和軸標籤的字體大小以及註釋的字體大小的函數?matplotlib中軸標籤文本頂部的位置是什麼?

具體地,給出與單個組刻度標記的和沿x軸的單軸標籤的圖,與字體分別尺寸tick_font_sizelabel_font_size,什麼是圖點的垂直位置y將導致

ax.annotate('Some text', (x, y), va='top', ...) 

放置'Some text'字體大小爲annotation_font_size,與軸標籤垂直對齊?


由於種種原因,我必須使用annotate對於這一點,並va='top'是一種約束;我需要使用上面的字體尺寸信息 - 即,我想找形式

y = f(tick_font_size, label_font_size, annotation_font_size) 

與圖點的所有值(即,可使用的與annotatetextcoords='offset points')的功能。這種算法必須存在,因爲matplotlib明確使用該算法將軸標籤放置在第一位。

+0

'top'不是ha的有效選項 – M4rtini

+0

@ M4rtini:正確;謝謝;固定。 – orome

回答

1

獲取設置xlabel時返回的對象。渲染圖形並使用get_position獲取標籤的位置。從那裏做一些轉換並添加註釋。

import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(10) 
y = x**2 

xlabel = plt.xlabel("test") 
plt.plot(x, y) 

ax = plt.gca() 
fig = plt.gcf() 
fig.draw(fig.canvas.get_renderer()) 

trans = xlabel.get_transform() 
xpos, ypos = trans.transform(xlabel.get_position()) # convert to display coordinates 
xpos, ypos = fig.transFigure.inverted().transform([xpos, ypos]) # convert to figure coordinates 
ax.annotate('Some text', (xpos+0.05, ypos), xycoords='figure fraction', va="top") 
plt.show() 
+0

假設我剛剛擁有'ax',並且已經設置了軸和標籤。我如何獲得'xlabel'? – orome

+0

ax.get_xaxis()。get_label() – M4rtini

+0

這是有幫助的,但不是我所期待的。我需要的是將'ax','tick_font_size','label_font_size'和'annotation_font_size'映射爲'y'的值,使註釋與軸標籤對齊。 (該函數存在,因爲它由'matplotlib'用來定位軸標籤。) – orome