问题
我的matplotlib应用程序生成用户定义的动态图像,因此页面标题文本之类的内容可以变化。我希望能够为matplotlib指定一个边界框,然后使其自动缩放字体大小,以使文本适合该边界框。我的应用程序仅使用AGG后端。
我的黑客解决方案
我是工具箱中最不熟练的工具,但这是我想出的解决此问题的方法。我蛮力地从50
的字体大小开始,然后向下迭代,直到我认为我可以将文本放入框中。
def fitbox(fig, text, x0, x1, y0, y1, **kwargs):
"""Fit text into a NDC box."""
figbox = fig.get_window_extent().transformed(
fig.dpi_scale_trans.inverted())
# need some slop for decimal comparison below
px0 = x0 * fig.dpi * figbox.width - 0.15
px1 = x1 * fig.dpi * figbox.width + 0.15
py0 = y0 * fig.dpi * figbox.height - 0.15
py1 = y1 * fig.dpi * figbox.height + 0.15
# print("px0: %s px1: %s py0: %s py1: %s" % (px0, px1, py0, py1))
xanchor = x0
if kwargs.get('ha', '') == 'center':
xanchor = x0 + (x1 - x0) / 2.
yanchor = y0
if kwargs.get('va', '') == 'center':
yanchor = y0 + (y1 - y0) / 2.
txt = fig.text(
xanchor, yanchor, text,
fontsize=50, ha=kwargs.get('ha', 'left'),
va=kwargs.get('va', 'bottom'),
color=kwargs.get('color', 'k')
)
for fs in range(50, 1, -2):
txt.set_fontsize(fs)
tbox = txt.get_window_extent(fig.canvas.get_renderer())
# print("fs: %s tbox: %s" % (fs, str(tbox)))
if (tbox.x0 >= px0 and tbox.x1 < px1 and tbox.y0 >= py0 and
tbox.y1 <= py1):
break
return txt
所以我可以像这样调用此函数
fitbox(fig, "Hello there, this is my title!", 0.1, 0.99, 0.95, 0.99)
问题/反馈请求
axes
中而不是整个图形中指定坐标。也许已经有效了:)顺便说一句,我喜欢其他一些绘图应用程序如何允许在无尺寸显示坐标中指定字体大小。例如,PyNGL。因此,您可以将其设置为fontsize=0.04
。
谢谢。