Python matplotlib获取边界框尺寸

时间:2017-02-17 09:44:11

标签: python matplotlib bounding-box

我正在尝试绘制一个图表,其中每个节点自动放置在其父节点下方1个单位。这是一个例子:

enter image description here

每个节点都是由边界框包围的文本,边界框可以有不同的大小,可能包含很多值(例如,框3非常长)。我需要获取每个父节点的底部坐标,并在其下面绘制子节点1单元。但是,我的问题是报告的边界框坐标不正确。在上面的例子中,我希望方框4比方框3低1个单位,但方框3的底部坐标报告为-1.5而不是-2.3。框4现在绘制得太接近其父级。我使用的是Python 2.7.13。这是我的代码:

import matplotlib.pyplot as plt

#instantiate plot
plt.axes()
ax = plt.gca()
ax.cla()

#simple setup: draw some nodes at predefined positions
t1 = ax.text(0, 0, '1', ha='center', va='top', color='black', bbox=dict(facecolor='#ccfff5', edgecolor='black',boxstyle='round,pad=0.5'),fontsize=8)
t2 = ax.text(-1, -1, '2', ha='center', va='top', color='black', bbox=dict(facecolor='#ccfff5', edgecolor='black',boxstyle='round,pad=0.5'),fontsize=8)
t3 = ax.text(1, -1, '3\n\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM', ha='center', va='top', color='black', bbox=dict(facecolor='#ccfff5', edgecolor='black',boxstyle='round,pad=0.5'),fontsize=8)

#draw edges between the nodes
plt.plot([0, 0],[0,0], zorder=1, color='#404040', linewidth=1)
plt.plot([0, -1],[0,-1], zorder=1, color='#404040', linewidth=1)
plt.plot([0, 1],[0,-1], zorder=1, color='#404040', linewidth=1)

#Obtain the dimensions of box 3 so that we can place box 4 properly underneath box 3
canvas = ax.figure.canvas
r = canvas.get_renderer()
transf = ax.transData.inverted()
bb = t3.get_window_extent(renderer = r)
bb_datacoords = bb.transformed(transf)

#The y0 coordinate of box 3 is not the expected bottom
print "box coordinates: ", bb_datacoords #Bbox(x0=0.978654233871, y0=-1.5130952381, x1=1.02134576613, y1=-1.0)
print "bottom of box 3: ", bb_datacoords.y0 #-1.5130952381

#define the top y coordinate of box 4
newY = (bb_datacoords.y0 - 1)
print "top position of box 4: ", newY #-2.5130952381
#the bottom coordinate of box 3
newPreviousY = bb_datacoords.y0
print "bottom position of box 3: ", newPreviousY #-1.5130952381

#Add box 4 1 unit below box 3
t4 = ax.text(1, newY, '4', ha='center', va='top', color='black', bbox=dict(facecolor='#ccfff5', edgecolor='black',boxstyle='round,pad=0.5'),fontsize=8)
plt.plot([1, 1],[newPreviousY,newY], zorder=1, color='#404040', linewidth=1)

plt.show()

通过在绘制绘图中的任何内容并将手动限制设置为:

之前禁用轴限制,我能够更接近解决此问题。
plt.xlim(-1, 1)
plt.ylim(-6, 1)
plt.autoscale(False)

然后框4仍然没有在框3下面精确地绘制1个单位(但我认为这是填充问题),但它几乎按预期工作。但是,事先设置轴限制并不理想,因为我需要自动绘制树,并且不知道该点的绘图限制应该是什么。

如何获得每个盒子的正确底部坐标并在其下方放置一个新盒子1个单位?

0 个答案:

没有答案