Matplotlib text bounding box dimensions

后端 未结 2 632
甜味超标
甜味超标 2020-12-18 00:44

What I want to do:

I want to get the position and dimensions of a text instance in matplotlib world units (not screen pixels), with the intention of calculating an

2条回答
  •  甜味超标
    2020-12-18 01:19

    This may help a bit.

    import matplotlib.pyplot as plt
    
    f = plt.figure()
    ax = f.add_subplot(111)
    ax.plot([0,10], [4,0])
    t = ax.text(3.2, 2.1, "testing...")
    
    # get the inverse of the transformation from data coordinates to pixels
    transf = ax.transData.inverted()
    bb = t.get_window_extent(renderer = f.canvas.renderer)
    bb_datacoords = bb.transformed(transf)
    
    # Bbox('array([[ 3.2       ,  2.1       ],\n       [ 4.21607125,  2.23034396]])')
    

    This should give what you want. If you want to have the coordinates in terms of figure coordinates (0..1,0..1), then use the inverse of ax.transAxes.

    However, there is a small catch in this solution. An excerpt from the matplotlib documentation:

    Any Text instance can report its extent in window coordinates (a negative x coordinate is outside the window), but there is a rub.

    The RendererBase instance, which is used to calculate the text size, is not known until the figure is drawn (draw()). After the window is drawn and the text instance knows its renderer, you can call get_window_extent().

    So, before the figure is really drawn, there seems to be no way to find out the text size.

    BTW, you may have noticed that the Bbox instances have method overlaps which may be used to find out whether the Bbox overlaps with another one (bb1.overlaps(bb2)). This may be useful in some cases, but it does not answer the question "how much".

    If you have rotated texts, you will have hard time seeing if they overlap, but that you probably already know.

提交回复
热议问题