简体   繁体   中英

How to get the width of a matplotlib text, including the padded bounding box?

I know how to get the width of the text:

import matplotlib.pyplot as plt
from matplotlib.patches import BoxStyle

xpos, ypos = 0, 0
text = 'blah blah'

boxstyle = BoxStyle("Round", pad=1)
props = {'boxstyle': boxstyle,
         'facecolor': 'white',
         'linestyle': 'solid',
         'linewidth': 1,
         'edgecolor': 'black'}

textbox = plt.text(xpos, ypos, text, bbox=props)
plt.show()
textbox.get_bbox_patch().get_width() # 54.121092459652573

However, this does not take into account the padding. Indeed, if I set the padding to 0, I get the same width.

boxstyle = BoxStyle("Round", pad=0)
props = {'boxstyle': boxstyle,
         'facecolor': 'white',
         'linestyle': 'solid',
         'linewidth': 1,
         'edgecolor': 'black'}

textbox = plt.text(xpos, ypos, text, bbox=props)
plt.show()
textbox.get_bbox_patch().get_width() # 54.121092459652573

My question is: how can I get the width of the surrounding box? or how can I get the size of the padding in the case of a FancyBoxPatch?

matplotlib.patches.FancyBboxPatch class is similar to matplotlib.patches.Rectangle class, but it draws a fancy box around the rectangle.

FancyBboxPatch.get_width() returns the width of the (inner) rectangle

However, FancyBboxPatch is a subclass of matplotlib.patches.Patch which provides a get_extents() method:

matplotlib.patches.Patch.get_extents()

Return a Bbox object defining the axis-aligned extents of the Patch.

Thus, what you need is textbox.get_bbox_patch().get_extents().width .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM