matplotlib: get text bounding box, independent of backend
Here is my solution/hack. @tcaswell suggested I look at how matplotlib handles saving figures with tight bounding boxes. I found the code for backend_bases.py on Github, where it saves the figure to a temporary file object simply in order to get the renderer from the cache. I turned this trick into a little function that uses the built-in method get_renderer()
if it exists in the backend, but uses the save method otherwise.
def find_renderer(fig):
if hasattr(fig.canvas, "get_renderer"):
#Some backends, such as TkAgg, have the get_renderer method, which
#makes this easy.
renderer = fig.canvas.get_renderer()
else:
#Other backends do not have the get_renderer method, so we have a work
#around to find the renderer. Print the figure to a temporary file
#object, and then grab the renderer that was used.
#(I stole this trick from the matplotlib backend_bases.py
#print_figure() method.)
import io
fig.canvas.print_pdf(io.BytesIO())
renderer = fig._cachedRenderer
return(renderer)
Here are the results using find_renderer()
with a slightly modified version of the code in my original example. With the TkAgg backend, which has the get_renderer()
method, I get:
With the MacOSX backend, which does not have the get_renderer()
method, I get:
Obviously, the bounding box using MacOSX backend is not perfect, but it is much better than the red box in my original question.