保存期间隐藏Matplotlib文本

时间:2013-08-15 17:22:05

标签: text matplotlib

我有一个'Paused'Matplotlib文本告诉用户图表已暂停。这很好用,但我不想在打印或保存时显示“暂停”这个词。

figPausedText = fig.text(0.5, 0.5,'Paused', horizontalalignment='center',
    verticalalignment='center',
    transform=ax.transAxes,
    alpha = 0.25,
    size='x-large')

保存/打印时隐藏暂停文本的最佳方法是什么?如果我可以绑定到所有保存和打印命令,我很高兴set_text('')。我特别想确保当用户点击NavigationToolbar2TkAgg工具栏时它可以正常工作。

1 个答案:

答案 0 :(得分:1)

这样的事情:

figPausedText = fig.text(...)
def my_save(fig, * args, **kwargs):
     figPausedText.set_visible(False)
     fig.savefig(*args, **kwargs)
     figPausedText.set_visible(True)

如果你想变得非常聪明,你可以修补你的Figure对象:

import types

figPausedText = fig.text(...)
# make sure we have a copy of the origanal savefig
old_save = matplotlib.figure.Figure.savefig
# our new function which well hide and then re-show your text
def my_save(fig, *args, **kwargs):
     figPausedText.set_visible(False)
     ret = old_save(fig, *args, **kwargs)
     figPausedText.set_visible(True)
     return ret
# monkey patch just this instantiation  
fig.savefig = types.MethodType(my_save, fig)

或者如果你需要这个来完成工具栏

import types

figPausedText = fig.text(...)
# make sure we have a copy of the origanal print_figure
old_print = fig.canvas.print_figure # this is a bound function
# if we want to do this right it is backend dependent
# our new function which well hide and then re-show your text
def my_save(canvas, *args, **kwargs):
     figPausedText.set_visible(False)
     ret = old_print(*args, **kwargs) # we saved the bound function, so don't need canvas
     figPausedText.set_visible(True)
     return ret
# monkey patch just this instantiation  
fig.canvas.print_figure = types.MethodType(my_save, fig.canvas)