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,9 +325,18 @@ 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 ]
328+ # Note also that we must extrapolate linearly beyond vmin/vmax
329+ min = self .vmin - (self .vcenter - self .vmin )
330+ max = self .vmax + (self .vmax - self .vcenter )
331+ x , y = [min , self .vcenter , max ], [- 0.5 , 0.5 , 1.5 ]
327332 return np .ma .masked_array (np .interp (value , x , y ))
328333
334+ def inverse (self , value ):
335+ min = self .vmin - (self .vcenter - self .vmin )
336+ max = self .vmax + (self .vmax - self .vcenter )
337+ y , x = [min , self .vcenter , max ], [- 0.5 , 0.5 , 1.5 ]
338+ return np .interp (value , x , y )
339+
329340
330341fig , ax = plt .subplots ()
331342midnorm = MidpointNormalize (vmin = - 500. , vcenter = 0 , vmax = 4000 )
@@ -334,5 +345,7 @@ def __call__(self, value, clip=None):
334345 cmap = terrain_map , shading = 'auto' )
335346ax .set_aspect (1 / np .cos (np .deg2rad (49 )))
336347ax .set_title ('Custom norm' )
337- fig .colorbar (pcm , shrink = 0.6 , extend = 'both' )
348+ cb = fig .colorbar (pcm , shrink = 0.6 , extend = 'both' )
349+ cb .set_ticks ([- 500 , 0 , 1000 , 2000 , 3000 , 4000 ])
350+
338351plt .show ()
0 commit comments