看来savefig
中的bbox_inches='tight'
选项会忽略没有文本的注释。这里是我的示例代码matplotlib:将图保存为bbox_inches ='tight'忽略注释
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0.2, 0.2, 0.6, 0.6])
arrow1 = ax.annotate('text', xy = [0.5,-0.2], xycoords = 'axes fraction', \
xytext = [-72,0], textcoords = 'offset points', \
arrowprops = dict(arrowstyle = '-|>', mutation_scale = 10.0, \
shrinkA = 0, shrinkB = 0, linewidth = 1))
arrow2 = ax.annotate('', xy = [0.5,1.2], xycoords = 'axes fraction', \
xytext = [-72,0], textcoords = 'offset points', \
arrowprops = dict(arrowstyle = '-|>', mutation_scale = 10.0, \
shrinkA = 0, shrinkB = 0, linewidth = 1))
fig.savefig('test.png')
fig.savefig('test-tight.png', bbox_inches = 'tight')
这里是test.png
,表明我有两个注释。一个注释,带有文字,轴下方,一个注释,没有文字,位于轴上方。
这里是test-tight.png
,仅显示一个注释。没有文字的轴上方的注释已被忽略。
寻找源代码,bbox_inches='tight'
尝试通过调用artist.get_window_extent()
找到艺术家的大小和位置。当我尝试arrow1.get_window_extent()
时,我会看到一个与文本相对应的边界框。当我尝试arrow2.get_window_extent()
时,我得到一个零高度和零宽度的边界框。因此,问题的根源是.get_window_extent()
不包括箭头。
有关如何以相当稳健的方式解决此问题的任何想法?如果我能以某种方式为整个注释获得适当的边界框,那么我将会开展业务。但是,我甚至无法从arrow2
中得到线或修补程序对象。
在它的事项的情况下,我在matplotlib 1.4.0,2.7.6的Python和Mac OS X 10.8.5