In [1]:
%matplotlib widget
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from mpl_interactions import zoom_factory, panhandler, ioff

Load a sample image

In [2]:
# A sample image
with cbook.get_sample_data('ada.png') as image_file:
    image = plt.imread(image_file)

enable scroll to zoom

Originally based on https://gist.github.com/tacaswell/3144287.

To use just pass the axis object to the zoom factory function. Here I also demonstrate using ioff as a context manager so we can control where the figure canvas shows up.

In [3]:
with ioff:
    fig, ax = plt.subplots()
ax.imshow(image)
disconnect_zoom = zoom_factory(ax)
display(fig.canvas)

Scrolling and panning

I like being able to pan by clicking with the mouse without having to click the toolbar. Below is an example demonstrating using the panhandler object allow scrolling using the middle mouse button though by changing the button attribute you can use any mouse button. You need to make sure to assign the panhanler to a variable otherwise it will be garbage collected and will not work.

In [4]:
pan_handler = panhandler(fig)
display(fig.canvas)
In [ ]: