首页 > 解决方案 > Matplotlib 文本艺术家 - 如何获得大小?(不使用 pyplot)

问题描述

背景

我已经移动了一些代码以仅使用 matplotlib不是 pyplot (原因是它在具有期货的多进程中生成 png 文件,而 pyplot 这样不是线程/进程安全的)。

所以我通过 matplotlib.Figure() 创建我的图形和轴,而不是通过 pyplot。

我有一些代码可以在图形上绘制文本“表格”,一侧右对齐,另一侧左对齐。为了保持两侧之间的间距不变,我之前get_window_extent()在我的左侧文本艺术家上使用来确定右侧的位置:

     # draw left text at figure normalised coordinates, right justified
     txt1 = figure.text(x, y, left_str,         
                        ha='right', color=left_color, fontsize=fontsize)
     # get the bounding box of that text - this is in display coords
     bbox = txt1.get_window_extent(renderer=figure.canvas.get_renderer())

     # get x location for right hand side offset from left's bbox
     trans = figure.transFigure.inverted()      
     xr, _ = trans.transform((bbox.x1 + spacing, bbox.y0))

     # draw right side text, using lhs's y value
     figure.text(xr, y, right_str,
                 ha='left', color=right_color, fontsize=fontsize)

问题

我现在的问题是我没有使用 pyplot,上面的代码无法工作,因为figure.canvas.get_renderer()无法返回渲染器,因为我没有设置渲染器,我只是使用 Figure.savefig(path) 来保存我的文件完了。


那么有没有办法在没有设置渲染器的情况下找出图中艺术家的边界框大小?


通过查看图例,它允许您使用具有可变文本大小的边界框线,我假设有,但我找不到如何。

我已经查看了https://matplotlib.org/3.1.3/tutorials/intermediate/artists.html,并且还尝试matplotlib.artist.getp(txt1)了上述内容,但没有找到任何看似有用的属性。

标签: python-3.xmatplotlib

解决方案


推荐阅读