Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib text dimensions

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 
like image 490
David Avatar asked Mar 16 '11 01:03

David


People also ask

How do I change the font size in matplotlib?

To change the font size of the scale in matplotlib, we can use labelsize in the ticks_params()method. To display the figure, use show() method.

What is default matplotlib font size?

Report Ad. Note: The default font size for all elements is 10.


2 Answers

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 
like image 78
David Avatar answered Sep 19 '22 09:09

David


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() 
like image 44
Paul Avatar answered Sep 20 '22 09:09

Paul