在matplotlib中获取数据坐标的边界框

8 投票
1 回答
10115 浏览
提问于 2025-04-16 14:36

我有一个 matplotlib.patches.Rectangle 对象的 bbox,这个对象是一个柱状图中的柱子,它的坐标是显示坐标,像这样:

Bbox(array([[ 0.,  0.],[ 1.,  1.]])

但是我想要的是数据坐标,而不是显示坐标。我很确定这需要进行转换。请问该怎么做呢?

1 个回答

19

我不太明白你是怎么得到显示坐标中的Bbox的。用户几乎所有的交互都是基于数据坐标(这些看起来像是坐标轴或数据坐标,而不是显示像素)。下面的内容应该能完整解释Bbox的转换过程:

from matplotlib import pyplot as plt
bars = plt.bar([1,2,3],[3,4,5])
ax = plt.gca()
fig = plt.gcf()
b = bars[0].get_bbox()  # bbox instance

print b
# box in data coords
#Bbox(array([[ 1. ,  0. ],
#       [ 1.8,  3. ]]))

b2 = b.transformed(ax.transData)
print b2
# box in display coords
#Bbox(array([[  80.        ,   48.        ],
#       [ 212.26666667,  278.4       ]]))

print b2.transformed(ax.transData.inverted())
# box back in data coords
#Bbox(array([[ 1. ,  0. ],
#       [ 1.8,  3. ]]))

print b2.transformed(ax.transAxes.inverted())
# box in axes coordinates
#Bbox(array([[ 0.        ,  0.        ],
#       [ 0.26666667,  0.6       ]]))

撰写回答