关于为什么很难将文本框的宽度设置为定义的宽度的争论,请参见此问题,该问题与设置标题文本框的宽度有关。原则上,也可以在此处使用该答案-
使其变得相当复杂。
一个相对简单的解决方案是在数据坐标中指定文本的x位置,在轴坐标中指定其y位置。这允许为具有相同坐标的文本创建一个矩形作为背景,使其看起来像文本的边框。
import matplotlib.pyplot as pltimport numpy as npind = [1,2,4,5]data = [4,5,6,4]perc = np.array(data)/float(np.array(data).sum())width=0.7 pad = 3 # pointsfig, ax = plt.subplots()bar = ax.bar(ind, data, width=width)fig.canvas.draw()for label, x in zip(perc, ind): text = ax.text( x, 1.00, '{:4.0%}'.format(label), ha="center", va="center" , transform=ax.get_xaxis_transform(), zorder=4) bb= ax.get_window_extent() h = bb.height/fig.dpi height = ((text.get_size()+2*pad)/72.)/h rect = plt.Rectangle((x-width/2.,1.00-height/2.), width=width, height=height, transform=ax.get_xaxis_transform(), zorder=3, fill=True, facecolor="lightblue", clip_on=False) ax.add_patch(rect)plt.show()


