matplotlib pan-scales the color bar axis
Matplotlib allows creating beautiful interactive plots. Dragging with the left mouse button allows us to pan the drawing left and right or up and down. Right-mouse button dragging allows us to zoom on an axis parallel to the direction in which you dragged the drawing. I would like to be able to replicate this behavior by dragging on the color bar. When the mouse is over the color bar, the little hand appears, but dragging does nothing. It would be great if dragging along the color bar with the left mouse button changes the color bar range (keeping the difference between cmin and cmax constant) and dragging with the right mouse button changes the difference between cmin and cmax (e.g. zoom), is there any way to do this?
So far, it looks like the solution will involve some form of callback function registered by fig.canvas.mpl_connect('button_press_event', func).
For example:
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)
It looks like these events are describedhere , but I can’t seem to figure out how to know if I’m on the color bar or the rest of the plot.
Solution
event.inaxes
is the axe of the 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()