matplotlib:使用bbox_inches ='tight'保存fig无视注释

时间:2014-10-12 04:40:43

标签: python matplotlib

bbox_inches='tight'中的savefig选项似乎忽略了没有文字的注释。这是我的示例代码

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,表明我有两个注释。一个注释,带有文本,位于轴下方,一个注释,没有文本,位于轴上方。

enter image description here

这是test-tight.png,只显示一个注释。没有文字的轴上方的注释已被忽略。

enter image description here

查看源代码,bbox_inches='tight'会尝试通过调用artist.get_window_extent()来查找艺术家的大小和位置。当我尝试arrow1.get_window_extent()时,我得到一个看起来与文本对应的边界框。当我尝试arrow2.get_window_extent()时,我得到一个零高度和零宽度的边界框。因此,问题的根源是.get_window_extent()不包含箭头。

如何以合理稳健的方式解决这个问题?如果我能够以某种方式获得整个注释的正确边界框,那么我就会开展业务。但是,我甚至无法从arrow2中获取线条或补丁对象。

如果重要,我在matplotlib 1.4.0,Python 2.7.6和Mac OS X 10.8.5上

2 个答案:

答案 0 :(得分:1)

我实际上在2014年将此错误报告为issue 3816,并在matplotlib v1.4.3中修复。很抱歉没有提前发布此结果。

答案 1 :(得分:0)

也许你可以尝试通过在注释命令中添加以下参数来创建边界框:bbox=dict(facecolor='none', edgecolor='none', pad=1.0) 或者,如果添加一些空格或白色字符,则尝试自动创建边界框。