Matplotlib文字尺寸

Dav*_*vid 30 python matplotlib

是否可以确定matplotlib文本对象的尺寸?如何找到像素的宽度和高度?

谢谢

编辑:我想我找到了一种方法来做到这一点.我在下面列举了一个例子.

import matplotlib as plt

f = plt.figure()
r = f.canvas.get_renderer()
t = plt.text(0.5, 0.5, 'test')

bb = t.get_window_extent(renderer=r)
width = bb.width
height = bb.height
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 13

即使在draw()事件之后,我找不到一种方法来获取在绘图上呈现的文本范围.

但这是一种只渲染文本并从中获取各种几何信息的方法:

t = matplotlib.textpath.TextPath((0,0), 'hello', size=9, prop='WingDings')
bb = t.get_extents()

#bb:
#Bbox(array([[  0.759375 ,   0.8915625],
#            [ 30.4425   ,   5.6109375]]))

w = bb.width   #29.683125
h = bb.height  #4.7193749
Run Code Online (Sandbox Code Playgroud)

编辑

我一直在玩这个,我有一个不一致的我无法弄清楚.也许别人可以提供帮助.规模似乎关闭,我不知道这是一个dpi问题或一个错误或什么,但这个例子几乎解释了:

import matplotlib
from matplotlib import pyplot as plt
plt.cla()

p = plt.plot([0,10],[0,10])

#ffam = 'comic sans ms'
#ffam = 'times new roman'
ffam = 'impact'
fp = matplotlib.font_manager.FontProperties(
    family=ffam, style='normal', size=30,
    weight='normal', stretch='normal')

txt = 'The quick brown fox'
plt.text(100, 100, txt, fontproperties=fp, transform=None)

pth = matplotlib.textpath.TextPath((100,100), txt, prop=fp)
bb = pth.get_extents()

# why do I need the /0.9 here??
rec = matplotlib.patches.Rectangle(
    (bb.x0, bb.y0), bb.width/0.9, bb.height/0.9, transform=None)
plt.gca().add_artist(rec)

plt.show()
Run Code Online (Sandbox Code Playgroud)


Dav*_*vid 11

from matplotlib import pyplot as plt

f = plt.figure()
r = f.canvas.get_renderer()
t = plt.text(0.5, 0.5, 'test')

bb = t.get_window_extent(renderer=r)
width = bb.width
height = bb.height
Run Code Online (Sandbox Code Playgroud)

  • bb.height在显示坐标中.如何在数据坐标中获得文本高度? (3认同)
  • @martinako,如果您使用的是 `Axes`,您可以获得一个从显示坐标转换为数据坐标的变换矩阵,如 `inv = ax.transData.inverted()`(其中 `ax` 是 `Axes` 实例) . 请参阅[转换教程](https://matplotlib.org/users/transforms_tutorial.html)。 (2认同)

Ami*_*mir 9

这是对已接受答案的一个小修改;

如果要获取轴坐标中的宽度和高度,可以使用以下命令:

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
r = fig.canvas.get_renderer()
t = ax.text(0.5, 0.5, 'test')

bb = t.get_window_extent(renderer=r).inverse_transformed(ax.transData)
width = bb.width
height = bb.height
Run Code Online (Sandbox Code Playgroud)

  • inverse_transformed 已弃用。请改用以下内容:`bb = t.get_window_extent(renderer=r).transformed(plt.gca().transData.inverted())` (4认同)
  • @mbrennwa 你也可以直接使用 `ax` 而不是 `plt.gca()`。 (2认同)

小智 8

感谢您的讨论。我可以将答案包装在一个函数中,以自动适应文本对象的字体大小,给定数据坐标中的宽度和高度(我认为这通常很有用,并希望在这里分享)。

文本与条形边缘重叠的示例:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.bar(0.5, 0.5, width=0.5)
text = ax.text(0.5, 0.5, 
                "0.5 (50.00 percent)", 
                va='top', ha='center', 
                fontsize=12)
ax.set_xlim(-0.5, 1.5)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

相反,自动调整文本对象的字体大小以适应条形宽度:

import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox

def auto_fit_fontsize(text, width, height, fig=None, ax=None):
    '''Auto-decrease the fontsize of a text object.

    Args:
        text (matplotlib.text.Text)
        width (float): allowed width in data coordinates
        height (float): allowed height in data coordinates
    '''
    fig = fig or plt.gcf()
    ax = ax or plt.gca()

    # get text bounding box in figure coordinates
    renderer = fig.canvas.get_renderer()
    bbox_text = text.get_window_extent(renderer=renderer)

    # transform bounding box to data coordinates
    bbox_text = Bbox(ax.transData.inverted().transform(bbox_text))

    # evaluate fit and recursively decrease fontsize until text fits
    fits_width = bbox_text.width < width if width else True
    fits_height = bbox_text.height < height if height else True
    if not all((fits_width, fits_height)):
        text.set_fontsize(text.get_fontsize()-1)
        auto_fit_fontsize(text, width, height, fig, ax)

fig, ax = plt.subplots()
ax.bar(0.5, 0.5, width=0.5)
text = ax.text(0.5, 0.5, 
                "0.5 (50.00 percent)", 
                va='top', ha='center', 
                fontsize=12)
ax.set_xlim(-0.5, 1.5)
auto_fit_fontsize(text, 0.5, None, fig=fig, ax=ax)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述