'Customizing the predefined callbacks of Matplotlib Navigation Toolbar buttons

I have GUI based interface where the user can select and unselect different properties to plot on a canvas, which is why it is important for me to use axis.autoscale_view every time a new plot is plotted. This seems to work fine until the use decides to zoom in a graph and then hits the home button and plots something new. After which for some reason the autoscale_view stops working.

For this reason, I want to embed this directly in the callback function of the home button provided in the navigation toolbar. Is it possible to modify the already created callback function of the home button in the navigation toolbar?



Solution 1:[1]

I just stumbled upon your question ... not sure if it's still relevant, but here's a hacky way how you could do it by decorating the toolbar._update_view function ...
(_update_view is called whenever the home or the change view buttons are pressed from the gui toolbar)

import matplotlib.pyplot as plt

f, ax = plt.subplots()
l, = ax.plot([1,2,3,4,5])

def update_decorator(f):
    def newf(*args, **kwargs):
        ret = f(*args, **kwargs)
        print("something happened")        
        return ret
    return newf

# decorate toolbar._update_view 
# (called whenever the home-button or the change-view button is pressed in a gui)
toolbar = f.canvas.toolbar
if toolbar is not None:
    toolbar._update_view = update_decorator(toolbar._update_view)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 raphael