如果有一种通用方法可以为任意 matplotlib 艺术家获取数据坐标中的边界框,我会发现它非常有用。
例如:
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle, Ellipse
import numpy as np
fig, ax = plt.subplots(1, 1)
r = Rectangle((0, 1), 3, 2, color='r')
e = Ellipse((1, 0), 4, 2, 30, color='g')
l = plt.plot(np.r_[1, 2, 0, 3, 2], c='b', lw=2)[0]
ax.add_patch(r)
ax.add_patch(e)
ax.set_xlim(-2, 5)
ax.set_ylim(-2, 4)
获取矩形的边界框非常简单 - 我可以使用它的
get_bbox()
方法:
print(r.get_bbox())
# [ 0. 1. 3. 3.]
但是,直线和椭圆都没有
get_bbox()
方法。对于这条线,我似乎可以做到:
print(l.get_path().get_extents().extents)
# [ 0. 0. 4. 3.]
但是相应的方法给了我一个错误的椭圆结果:
print(e.get_path().get_extents().extents)
# [-1. -1. 1. 1.]
迄今为止我发现的最好的“通用”方法是基于这个答案,并使用
get_window_extent()
获取显示空间中的边界框,然后逆轴数据转换转换回数据坐标:
def get_bbox_generic(a):
fig, ax = a.figure, a.axes
disp = a.get_window_extent(renderer=fig.canvas.renderer)
return disp.transformed(ax.transData.inverted())
但是这种方法至少有几个缺点:除非图形之前已经渲染过,否则它会失败,并且转换后的坐标有点不精确。
有更好的方法吗?
从
matplotlib >= 3.6
开始,有 Ellipse.get_corners()
和 Line2D.get_bbox()
方法。
Ellipse.get_corners()
方法返回数据坐标中椭圆边界框的 4 个角点:
from matplotlib.patches import Ellipse
e = Ellipse((1, 0), 4, 2, color='g')
print(e.get_corners())
# [[-1., -1.],
# [ 3., -1.],
# [ 3., 1.],
# [-1., 1.]]
Line2D.get_bbox()
方法返回直线边界框的两个点:
import numpy as np
from matplotlib import pyplot as plt
l = plt.plot(np.r_[1, 2, 0, 3, 2], c='b', lw=2)[0]
print(l.get_bbox())
# Bbox(x0=0.0, y0=0.0, x1=4.0, y1=3.0)