1

我有一个“暂停”的 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 工具栏时有效。

4

1 回答 1

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)
于 2013-08-15T18:28:21.297 回答