|
| 1 | +""" |
| 2 | +======================================== |
| 3 | +Interactive Adjustment of Colormap Range |
| 4 | +======================================== |
| 5 | +
|
| 6 | +Demonstration of using colorbar and picker functionality to make an |
| 7 | +interactively adjustable colorbar widget. |
| 8 | +""" |
| 9 | + |
| 10 | +import numpy as np |
| 11 | +import matplotlib.pyplot as plt |
| 12 | +from matplotlib.backend_bases import MouseButton |
| 13 | + |
| 14 | + |
| 15 | +def pick_fn(event): |
| 16 | + adjust_colorbar(event.mouseevent) |
| 17 | + |
| 18 | + |
| 19 | +def motion_fn(mouseevent): |
| 20 | + if mouseevent.inaxes is colorbar.ax.axes: |
| 21 | + adjust_colorbar(mouseevent) |
| 22 | + |
| 23 | + |
| 24 | +def adjust_colorbar(mouseevent): |
| 25 | + if mouseevent.button == MouseButton.LEFT: |
| 26 | + colorbar.norm.vmax = max(mouseevent.ydata, colorbar.norm.vmin) |
| 27 | + elif mouseevent.button == MouseButton.RIGHT: |
| 28 | + colorbar.norm.vmin = min(mouseevent.ydata, colorbar.norm.vmax) |
| 29 | + else: |
| 30 | + # discard all others |
| 31 | + return |
| 32 | + |
| 33 | + canvas.draw_idle() |
| 34 | + |
| 35 | + |
| 36 | +fig, ax = plt.subplots() |
| 37 | +canvas = fig.canvas |
| 38 | +arr = np.random.random((100, 100)) |
| 39 | +axesimage = plt.imshow(arr) |
| 40 | +colorbar = plt.colorbar(axesimage, ax=ax, use_gridspec=True) |
| 41 | + |
| 42 | +# helps you see what value you are about to set the range to |
| 43 | +colorbar.ax.set_navigate(True) |
| 44 | + |
| 45 | +# React to all motion with left or right mouse buttons held |
| 46 | +canvas.mpl_connect("motion_notify_event", motion_fn) |
| 47 | + |
| 48 | +# React only to left and right clicks |
| 49 | +colorbar.ax.axes.set_picker(True) |
| 50 | +canvas.mpl_connect("pick_event", pick_fn) |
| 51 | + |
| 52 | +plt.show() |
0 commit comments