277277# longitude depends on latitude.
278278ax .set_aspect (1 / np .cos (np .deg2rad (49 )))
279279ax .set_title ('TwoSlopeNorm(x)' )
280- fig .colorbar (pcm , shrink = 0.6 )
280+ cb = fig .colorbar (pcm , shrink = 0.6 )
281+ cb .set_ticks ([- 500 , 0 , 1000 , 2000 , 3000 , 4000 ])
281282plt .show ()
282283
283284
@@ -312,7 +313,8 @@ def _inverse(x):
312313# ----------------------------------------------------------
313314#
314315# The `.TwoSlopeNorm` described above makes a useful example for
315- # defining your own norm.
316+ # defining your own norm. Note for the colorbar to work, you must
317+ # define an inverse for your norm:
316318
317319
318320class MidpointNormalize (colors .Normalize ):
@@ -323,8 +325,14 @@ def __init__(self, vmin=None, vmax=None, vcenter=None, clip=False):
323325 def __call__ (self , value , clip = None ):
324326 # I'm ignoring masked values and all kinds of edge cases to make a
325327 # simple example...
326- x , y = [self .vmin , self .vcenter , self .vmax ], [0 , 0.5 , 1 ]
327- return np .ma .masked_array (np .interp (value , x , y ))
328+ # Note also that we must extrapolate beyond vmin/vmax
329+ x , y = [self .vmin , self .vcenter , self .vmax ], [0 , 0.5 , 1. ]
330+ return np .ma .masked_array (np .interp (value , x , y ,
331+ left = - np .inf , right = np .inf ))
332+
333+ def inverse (self , value ):
334+ y , x = [self .vmin , self .vcenter , self .vmax ], [0 , 0.5 , 1 ]
335+ return np .interp (value , x , y , left = - np .inf , right = np .inf )
328336
329337
330338fig , ax = plt .subplots ()
@@ -334,5 +342,7 @@ def __call__(self, value, clip=None):
334342 cmap = terrain_map , shading = 'auto' )
335343ax .set_aspect (1 / np .cos (np .deg2rad (49 )))
336344ax .set_title ('Custom norm' )
337- fig .colorbar (pcm , shrink = 0.6 , extend = 'both' )
345+ cb = fig .colorbar (pcm , shrink = 0.6 , extend = 'both' )
346+ cb .set_ticks ([- 500 , 0 , 1000 , 2000 , 3000 , 4000 ])
347+
338348plt .show ()
0 commit comments