mpl-pan-zoom#
A tiny library for enabling scroll to zoom and click to pan for matplotlib
Installation#
pip install mpl-pan-zoom
Zooming and Panning#
%matplotlib widget
import matplotlib.pyplot as plt
from mpl_pan_zoom import PanManager, zoom_factory, MouseButton
from matplotlib.cbook import get_sample_data
Load a sample image#
with get_sample_data('grace_hopper.jpg') as image_file:
image = plt.imread(image_file)
enable scroll to zoom#
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.
fig, ax = plt.subplots(constrained_layout=True)
ax.imshow(image)
ax.axis('off')
disconnect_zoom = zoom_factory(ax)
Scrolling and panning#
You can enable the click and drag behvior to be panning without having to selec the button on the toolbar using PanManager
Chose which mouse button is used with the button
argument.
Note
You must assign the PanManager to a variable otherwise it will be garbage collected and will not work.
from mpl_pan_zoom import MouseButton
pan_manager = PanManager(fig, MouseButton.MIDDLE)
display(fig.canvas)
It’s also possible to enable and disable the PanManager
:
pan_handler.disable()
pan_handler.enable()