matplotlib: get text bounding box, independent of backend

前端 未结 2 1879
孤街浪徒
孤街浪徒 2020-12-09 20:03

I would like to get the bounding box (dimensions) around some text in a matplotlib figure. The post here, helped me realize that I can use the method text.get_window_

2条回答
  •  时光取名叫无心
    2020-12-09 20:53

    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.

提交回复
热议问题