如何在Matplotlib中获取包装文本的高度?

时间:2018-06-07 13:27:07

标签: python matplotlib

我有一个suptitle对象,有时会使用Matplotlib的内置包装功能进行包装。然而,当试图获得suptitle的高度时,我似乎总是得到对应于一条线的高度。我哪里错了?这就是我正在尝试的:

from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

fig = Figure((4, 4))
FigureCanvas(fig)

text_1 = "I'm a short text"
text_2 = "I'm a longer text that will be wrapped autoamtically by Matplotlib, using wrap=True"

title = fig.suptitle(text_1, wrap=True)
fig.canvas.draw()  # Draw text to find out how big it is
bbox = title.get_window_extent()
print(bbox.width)  # 105
print(bbox.height)  # 14

title = fig.suptitle(text_2, wrap=True)
fig.canvas.draw()  # Draw text to find out how big it is
bbox = title.get_window_extent()
print(bbox.width)  # 585 <-- This looks about right
print(bbox.height)  # Still 14 even though this time the text is wrapped!

同样的事情发生在Text个对象上(使用fig.text(0.5, 0.5, text_1, wrap=True)

之类的东西

1 个答案:

答案 0 :(得分:0)

感谢@ImportanceOfBeingErnest指出这不可能。这是一种解决方法,通过检查文本被分解成的行数,并乘以近似的行高来实现这种工作。当自动插入的断点与手动混合时(即文本中有"\n"),这将起作用,但会被多个像素关闭。欢迎任何更精确的建议。

def get_text_height(fig, obj):
    """ Get the approximate height of a text object.
    """
    fig.canvas.draw()  # Draw text to find out how big it is
    t = obj.get_text()
    r = fig.canvas.renderer
    w, h, d = r.get_text_width_height_descent(t, obj._fontproperties,
                                              ismath=obj.is_math_text(t))
    num_lines = len(obj._get_wrapped_text().split("\n"))
    return (h * num_lines)

text = "I'm a long text that will be wrapped automatically by Matplotlib, using wrap=True"
obj = fig.suptitle(text, wrap=True)
height = get_text_height(fig, obj)
print(height)  # 28 <-- Close enough! (In reality 30)