Matplotlib text dimensions


Question

Is it possible to determine the dimensions of a matplotlib text object? How can I find the width and height in pixels?

Thanks

Edit: I think I figured out a way to do this. I've included an example below.

import matplotlib as plt

f = plt.figure()
r = f.canvas.get_renderer()
t = plt.text(0.5, 0.5, 'test')

bb = t.get_window_extent(renderer=r)
width = bb.width
height = bb.height
1
30
7/17/2015 12:52:07 PM

Accepted Answer

from matplotlib import pyplot as plt

f = plt.figure()
r = f.canvas.get_renderer()
t = plt.text(0.5, 0.5, 'test')

bb = t.get_window_extent(renderer=r)
width = bb.width
height = bb.height
11
3/22/2019 7:36:09 PM

I could not find a way to get the text extents as rendered on a plot even after a draw() event.

But here's a way to render just the text and get all kinds of geometric information from it:

t = matplotlib.textpath.TextPath((0,0), 'hello', size=9, prop='WingDings')
bb = t.get_extents()

#bb:
#Bbox(array([[  0.759375 ,   0.8915625],
#            [ 30.4425   ,   5.6109375]]))

w = bb.width   #29.683125
h = bb.height  #4.7193749

Edit

I've been playing with this for a bit and I have an inconsistency I can't get figured out. Maybe someone else can help. The scale seems off and I don't know if it's a dpi issue or a bug or what, but this example pretty much explains:

import matplotlib
from matplotlib import pyplot as plt
plt.cla()

p = plt.plot([0,10],[0,10])

#ffam = 'comic sans ms'
#ffam = 'times new roman'
ffam = 'impact'
fp = matplotlib.font_manager.FontProperties(
    family=ffam, style='normal', size=30,
    weight='normal', stretch='normal')

txt = 'The quick brown fox'
plt.text(100, 100, txt, fontproperties=fp, transform=None)

pth = matplotlib.textpath.TextPath((100,100), txt, prop=fp)
bb = pth.get_extents()

# why do I need the /0.9 here??
rec = matplotlib.patches.Rectangle(
    (bb.x0, bb.y0), bb.width/0.9, bb.height/0.9, transform=None)
plt.gca().add_artist(rec)

plt.show()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon