Matplotlib doesn't provide 'home', 'back' or 'forward' button event.
To add a callback that will be called with 'home', 'back' or 'forward' button event, a common approach is to subclass a matplotlib backend.
But I am not in favor of this approach. I think it has two cons:
- If you want to use different backends, you have to subclass each of them.
- Deploy your own backend outside of matplotlib is not trivial. Your backend has to be a module which must be in the PYTHONPATH.
Since none of backends provided by matplotlib overrides NavigationToolbar2
's home
, back
and forward
methods. I prefer the more concise monkey-patched approach.
For example, you can replace NavigationToolbar2
's home
by your own method.
import matplotlib.pyplot as plt
from matplotlib.backend_bases import NavigationToolbar2
home = NavigationToolbar2.home
def new_home(self, *args, **kwargs):
print 'new home'
home(self, *args, **kwargs)
NavigationToolbar2.home = new_home
fig = plt.figure()
plt.text(0.35, 0.5, 'Hello world!', dict(size=30))
plt.show()
We can even mimic matplotlib's mpl_connect
style.
import matplotlib.pyplot as plt
from matplotlib.backend_bases import NavigationToolbar2, Event
home = NavigationToolbar2.home
def new_home(self, *args, **kwargs):
s = 'home_event'
event = Event(s, self)
event.foo = 100
self.canvas.callbacks.process(s, event)
home(self, *args, **kwargs)
NavigationToolbar2.home = new_home
def handle_home(evt):
print 'new home'
print evt.foo
fig = plt.figure()
fig.canvas.mpl_connect('home_event', handle_home)
plt.text(0.35, 0.5, 'Hello world!', dict(size=30))
plt.show()