3
3
Interactive Adjustment of Colormap Range
4
4
========================================
5
5
6
- Demonstration of using colorbar and picker functionality to make an
6
+ Demonstration of using colorbar, picker, and event functionality to make an
7
7
interactively adjustable colorbar widget.
8
+
9
+ Left clicks and drags inside the colorbar axes adjust the high range of the
10
+ color scheme. Likewise, right clicks and drags adjust the low range. The
11
+ connected AxesImage immediately updates to reflect the change.
8
12
"""
9
13
10
14
import numpy as np
11
15
import matplotlib .pyplot as plt
12
16
from matplotlib .backend_bases import MouseButton
13
17
14
18
15
- def pick_fn (event ):
19
+ def on_pick (event ):
16
20
adjust_colorbar (event .mouseevent )
17
21
18
22
19
- def motion_fn (mouseevent ):
20
- if mouseevent .inaxes is colorbar .ax . axes :
23
+ def on_move (mouseevent ):
24
+ if mouseevent .inaxes is colorbar .ax :
21
25
adjust_colorbar (mouseevent )
22
26
23
27
@@ -35,18 +39,29 @@ def adjust_colorbar(mouseevent):
35
39
36
40
fig , ax = plt .subplots ()
37
41
canvas = fig .canvas
38
- arr = np .random .random ((100 , 100 ))
39
- axesimage = plt .imshow (arr )
42
+
43
+ delta = 0.1
44
+ x = np .arange (- 3.0 , 4.001 , delta )
45
+ y = np .arange (- 4.0 , 3.001 , delta )
46
+ X , Y = np .meshgrid (x , y )
47
+ Z1 = np .exp (- X ** 2 - Y ** 2 )
48
+ Z2 = np .exp (- (X - 1 )** 2 - (Y - 1 )** 2 )
49
+ Z = (0.9 * Z1 - 0.5 * Z2 ) * 2
50
+
51
+ cmap = plt .get_cmap ('viridis' ).with_extremes (over = 'xkcd:orange' , under = 'xkcd:dark red' )
52
+ axesimage = plt .imshow (Z , cmap = cmap )
40
53
colorbar = plt .colorbar (axesimage , ax = ax , use_gridspec = True )
41
54
42
- # helps you see what value you are about to set the range to
55
+ # `set_navigate` helps you see what value you are about to set the range
56
+ # to, and enables zoom and pan in the colorbar which can be helpful for
57
+ # narrow or wide data ranges
43
58
colorbar .ax .set_navigate (True )
44
59
45
60
# React to all motion with left or right mouse buttons held
46
- canvas .mpl_connect ("motion_notify_event" , motion_fn )
61
+ canvas .mpl_connect ("motion_notify_event" , on_move )
47
62
48
63
# React only to left and right clicks
49
- colorbar .ax .axes . set_picker (True )
50
- canvas .mpl_connect ("pick_event" , pick_fn )
64
+ colorbar .ax .set_picker (True )
65
+ canvas .mpl_connect ("pick_event" , on_pick )
51
66
52
67
plt .show ()
0 commit comments