2017-06-12 174 views
1

在下面的代碼中,我使用get_window_extent()來獲取文本標籤的高度。爲了使屏幕顯示和字體大小具有1:1的關係,我已將圖像dpi值設置爲72 dpi。我的期望是由get_window_extent()檢索的值將匹配文本點大小值。matplotlib get_window_extent()獲取錯誤的文本高度

爲了測試這一點,我創建了一個循環來繪製一組增加大小的文本標籤,我發現get_window_extent()檢索到的值與某些字體大小相匹配,但不適用於其他大小。

這裏是通過下面的代碼所產生的輸出:

Font Size 
Set Returned 
9 9.0 
10 10.0 
11 10.0 
12 13.0 
13 13.0 
14 14.0 
15 15.0 
16 15.0 
17 18.0 
18 18.0 

看來任一圖中dpi設置實際上不是在72 DPI,或出了某種錯誤與get_window_extent()方法。

我在macOS 10.12.5上運行Matplotlib 1.5.0,使用WXagg後端。爲什麼會發生這種情況的任何想法都會受到歡迎。

import matplotlib as mpl 
mpl.use('wxagg') 
import matplotlib.pyplot as plt 

# points per inch 
points_per_inch = 72 

# set figure size in inches 
myfsize = (8, 6) 

# create figure and subplot axes matrix 
myfig, ax = plt.subplots(1, 1, dpi=72, figsize=myfsize) 

# adjust subplot spacing 
plt.subplots_adjust(wspace=0.04, hspace=0.04, right=0.8, 
        bottom=0.1, top=0.9, left=0.125) 

# draw canvase to get positions 
plt.gcf().canvas.draw() 

string = 'curve' 

print 
print 'Font Size' 
print 'Set', '\t', 'Returned' 

# loop over a range of font sizes and print retrieved font size 
for i in range(10): 
    text_size = 9 + i 
    text_position = i/10.0 
    txt = ax.text(0.0, text_position, string, fontsize=text_size, 
        transform=ax.transAxes) 
    plt.gcf().canvas.draw() 
    txt_height_display = txt.get_window_extent().height 
    print text_size, '\t', txt_height_display 

plt.show() 

回答

0

由於文本在屏幕像素上的離散化,字體填充的像素數量和字體大小之間總會有偏差。這種偏差可能會上升2個像素 - 每邊一個。
因此,我不會擔心或得到你所得到的結果。

+0

謝謝,我在兩個顏色的相同位置繪製了兩個相同的文本字符串,點大小爲17和18,並且觀察到屏幕上的高度相同(寬度不同)。 – jkueng