Last active
October 14, 2020 19:44
-
-
Save ianhi/5f514c31f13cc28fbd167849867122b7 to your computer and use it in GitHub Desktop.
add right click drag to pan to matplotlib imshow. Now available via https://github.com/ianhi/mpl-interactions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class panhandler: | |
""" | |
enable click to pan image. | |
button determines which button will be used (default right click) | |
Left: 1 | |
Middle: 2 | |
Right: 3 | |
""" | |
def __init__(self, fig, button=3): | |
self.fig = fig | |
self._id_drag = None | |
self.button = 2 | |
self.fig.canvas.mpl_connect('button_press_event', self.press) | |
self.fig.canvas.mpl_connect('button_release_event', self.release) | |
def _cancel_action(self): | |
self._xypress = [] | |
if self._id_drag: | |
self.fig.canvas.mpl_disconnect(self._id_drag) | |
self._id_drag = None | |
def press(self, event): | |
if event.button != self.button: | |
self._cancel_action() | |
return | |
x, y = event.x, event.y | |
self._xypress = [] | |
for i, a in enumerate(self.fig.get_axes()): | |
if (x is not None and y is not None and a.in_axes(event) and | |
a.get_navigate() and a.can_pan()): | |
a.start_pan(x, y, event.button) | |
self._xypress.append((a, i)) | |
self._id_drag = self.fig.canvas.mpl_connect( | |
'motion_notify_event', self._mouse_move) | |
def release(self, event): | |
self._cancel_action() | |
self.fig.canvas.mpl_disconnect(self._id_drag) | |
for a, _ind in self._xypress: | |
a.end_pan() | |
if not self._xypress: | |
self._cancel_action() | |
return | |
self._cancel_action() | |
def _mouse_move(self, event): | |
for a, _ind in self._xypress: | |
# safer to use the recorded button at the _press than current | |
# button: # multiple button can get pressed during motion... | |
a.drag_pan(1, event.key, event.x, event.y) | |
self.fig.canvas.draw_idle() |
Good portions of this are taken from the panning option from the toolbar https://github.com/matplotlib/matplotlib/blob/1b12cd5651283ea49665a95308d0bb6a430f62e8/lib/matplotlib/backend_bases.py#L3046
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pairs well with https://gist.github.com/ianhi/b638e09fa7a00764ea539940a0519af9