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
4 个回答
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
12
我找不到一种方法来获取在图表上渲染的文本的大小,即使在调用了 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
编辑
我玩了这个一段时间,但遇到了一些不一致的地方,我搞不明白。也许其他人可以帮忙。比例似乎不对,我不知道这是 dpi 问题、bug 还是其他什么,但这个例子大致解释了:
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()
30
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在另一个地方使用它。这就像你从冰箱拿出食材,然后在厨房里做饭一样。
有些时候,我们会遇到一些问题,比如数据的格式不对,或者数据没有按我们想要的方式排列。这就像你在做饭时发现食材切得不够好,可能需要重新切一下。
为了避免这些问题,程序员们会使用一些工具和方法来确保数据是正确的。这就像在做饭前先准备好所有的食材,确保一切都在正确的位置。
总之,处理数据就像做饭一样,需要仔细准备和处理,才能做出美味的菜肴。
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