Search code examples
python-2.7matplotlibmacos-sierra

matplotlib get_window_extent() gets wrong text height


In the code below I'm using get_window_extent() to get the height of a text label. I have set the figure dpi value to 72 dpi in an attempt to make the screen display and font size have a 1:1 relationship. My expectation is that the value retrieved by get_window_extent() would match the text point size value.

To test this out I created a loop to draw a set of text labels of increasing size and I'm finding that the value retrieved by get_window_extent() matches for some font sizes but not for others.

Here is the output produced by the code below:

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

It appears that either the figure dpi setting is not actually at 72 dpi, or that something is amiss with the get_window_extent() method.

I'm running Matplotlib 1.5.0 on macOS 10.12.5, using the WXagg backend. Any ideas as why this is occurring would be welcome.

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

Solution

  • Due to the discretization of the text onto screen pixels, there may always be a deviation between the number of pixels filled by the font and the fontsize. This deviation may be up tp 2 pixels - one to each side.
    I therefore wouldn't be worried or supprised by the results you get.