matplotlib get_window_extent() 获取错误的文本高度

matplotlib get_window_extent() gets wrong text height

在下面的代码中,我使用 get_window_extent() 来获取文本标签的高度。我将图形dpi值设置为72dpi,试图让屏幕显示和字体大小有一个1:1的关系。我的期望是 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()

由于文本在屏幕像素上的离散化,字体填充的像素数与字体大小之间可能始终存在偏差。此偏差可能高达 tp 2 个像素 - 每侧一个。
因此,我不会对您得到的结果感到担心或惊讶。