mgilson
mgilson

Reputation: 310117

matplotlib pan-zoom colorbar axis

Matplotlib allows for the creation of nice interactive plots. Dragging while holding the left mouse button allows us to pan the plot left-right or top-bottom. Dragging while holding the right mouse button allows us to zoom on the axis parallel to the direction that you drag the plot. I would like to be able to replicate this sort of behavior by dragging on the colorbar. When the mouse is over the colorbar, the little hand appears, but dragging does nothing. It would be nice if dragging along the colorbar with the left mouse button would change the colorbar range (keeping the difference between cmin and cmax constant) and dragging with the right mouse button would change the difference between cmin and cmax (e.g. zoom) Is there any way for this to be possible?

Thus far, it looks like the solution will involve some form of callback function registered by fig.canvas.mpl_connect('button_press_event', func). e.g.:

def onclick(event):
    tb = plt.get_current_fig_manager().toolbar
    print repr(tb.mode),bool(tb.mode)
    if tb.mode != '':
        print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
            event.button, event.x, event.y, event.xdata, event.ydata)

cid = fig.canvas.mpl_connect('button_press_event', onclick)

And it looks like the events are described here, but I can't seem to figure out how to know if I'm on the colorbar or the rest of the plot.

Upvotes: 3

Views: 1984

Answers (1)

HYRY
HYRY

Reputation: 97331

event.inaxes is the axe of current event:

import numpy as np
from matplotlib import pyplot as plt
from functools import partial

def onclick_cbar(cbar, event):
    if event.inaxes is cbar.ax:
        print cbar.mappable
        print cbar.mappable.get_clim()
        print event.xdata, event.ydata

fig = plt.figure()
y, x = np.mgrid[-1:1:100j, -1:1:100j]
z = np.sin(x**2 + y**2)
pcm = plt.pcolormesh(x, y, z)
cbar = plt.colorbar()
cid = fig.canvas.mpl_connect('button_press_event', partial(onclick_cbar, cbar))
plt.show()

Upvotes: 4

Related Questions