1+ import matplotlib .pyplot as plt
2+ import matplotlib .colors as colors
3+ import numpy as np
4+
5+ """
6+ The NDVI values will range from -1 to 1. You want to use a diverging color scheme to visualize the data,
7+ and you want to center the colorbar at a defined midpoint. The class below allows you to normalize the colorbar.
8+ """
9+ class MidpointNormalize (colors .Normalize ):
10+ """
11+ Normalise the colorbar so that diverging bars work there way either side from a prescribed midpoint value)
12+ e.g. im=ax1.imshow(array, norm=MidpointNormalize(midpoint=0.,vmin=-100, vmax=100))
13+ Credit: Joe Kington, http://chris35wills.github.io/matplotlib_diverging_colorbar/
14+ Credit: https://stackoverflow.com/a/48598564
15+ """
16+ def __init__ (self , vmin = None , vmax = None , midpoint = None , clip = False ):
17+ self .midpoint = midpoint
18+ colors .Normalize .__init__ (self , vmin , vmax , clip )
19+
20+ def __call__ (self , value , clip = None ):
21+ # Note that I'm ignoring clipping and other edge cases here.
22+ result , is_scalar = self .process_value (value )
23+ x , y = [self .vmin , self .midpoint , self .vmax ], [0 , 0.5 , 1 ]
24+ return np .ma .array (np .interp (value , x , y ), mask = result .mask , copy = False )
25+
26+
27+ def show_ndvi (ndvi , figsize = (20 , 10 )):
28+ fig = plt .figure (figsize = figsize )
29+ ax = fig .add_subplot (111 )
30+
31+ # diverging color scheme chosen from https://matplotlib.org/users/colormaps.html
32+ cmap = plt .cm .RdYlGn
33+
34+ mmin = np .nanmin (ndvi )
35+ mmax = np .nanmax (ndvi )
36+ mid = 0
37+
38+ cax = ax .imshow (ndvi , cmap = cmap , clim = (mmin , mmax ),
39+ norm = MidpointNormalize (midpoint = mid ,vmin = mmin , vmax = mmax ))
40+
41+ ax .axis ('off' )
42+ ax .set_title ('Normalized Difference Vegetation Index' , fontsize = 18 , fontweight = 'bold' )
43+
44+ cbar = fig .colorbar (cax , orientation = 'horizontal' , shrink = 0.5 )
45+
46+ plt .show ()
0 commit comments