2017-09-13 105 views
1

的Line2D高度我有例如下面的行matplotlib繪製Matplotlib:以像素爲單位

import matplotlib.pyplot as plt 
fig = plt.figure() 
ax = fig.add_subplot(2,1,1) # two rows, one column, first plot 
# This should be a straight line which spans the y axis 
# from 0 to 50 
line, = ax.plot([0]*50, range(50), color='blue', lw=2) 
line2, = ax.plot([10]*100, range(100), color='blue', lw=2) 

我怎麼能得到多少像素是直線,在y方向?

注意:我有幾條這些線之間存在空隙,我想將文本放在它們旁邊,但是,如果線條太多,我需要知道可以添加多少文本,即我需要線條的高度的原因。

例如在附圖中,右側有一條藍線,高度約爲160像素。在160像素的高度(使用我使用的字體)時,我可以放入大約8行文字,因爲文字高度大約爲12像素高。

如何獲取有關線條像素高度的信息?還是有更好的方法來擺脫文字?

Text next to a straight line

+0

感謝您的評論就行了。 – Har

+0

這是專門針對直線的像素,而不是樣條線。 – Har

回答

1

爲了獲得以像素爲單位,您可以使用其邊框的單位線的高度。爲確保邊界框是畫布上繪製的線條的邊框,首先需要繪製畫布。然後通過.line2.get_window_extent()獲得邊界框。邊界框上端(y1)與下端(y0)之間的差異就是您要查找的像素數。

fig.canvas.draw() 
bbox = line2.get_window_extent(fig.canvas.get_renderer()) 
# at this point you can get the line height: 
print "Lineheight in pixels: ", bbox.y1 - bbox.y0 

爲了在該行的y範圍內繪製文本,以下內容可能會有用。給定點的字體大小,例如fontsize = 12,您可以計算像素的大小,然後計算可能的文本行數以適合上面確定的像素範圍。使用混合變換,其中x以數據單位爲單位,y以像素爲單位允許您以數據單位(此處爲x=8)指定x座標,但以直線的範圍計算座標中的y座標(以像素爲單位)。

import matplotlib.pyplot as plt 
import matplotlib.transforms as transforms 

fig = plt.figure() 
ax = fig.add_subplot(2,1,1) 

line, = ax.plot([0]*50, range(50), color='blue', lw=2) 
line2, = ax.plot([10]*100, range(100), color='blue', lw=2) 

fig.canvas.draw() 
bbox = line2.get_window_extent(fig.canvas.get_renderer()) 
# at this point you can get the line height: 
print "Lineheight in pixels: ", bbox.y1 - bbox.y0 

#To draw text 
fontsize=12 #pt 
# fontsize in pixels: 
fs_pixels = fontsize*fig.dpi/72. 
#number of possible texts to draw: 
n = (bbox.y1 - bbox.y0)/fs_pixels 
# create transformation where x is in data units and y in pixels 
trans = transforms.blended_transform_factory(ax.transData, transforms.IdentityTransform()) 
for i in range(int(n)): 
    ax.text(8.,bbox.y0+(i+1)*fs_pixels, "Text", va="top", transform=trans) 


plt.show() 

enter image description here

相關問題