Python Contour Plot with Discrete Colorbar

In this post, we create un-evenly distributed discrete colorbar, and also set the color for outbound contour values. Please check the attached python script:
Here is the generated contour plot:
User could also download the Docker image for this recipe from dockerhub, and run the recipe using jupyter nootbook:
https://hub.docker.com/r/podaacdatarecipes/colorbar_discrete/
- Code: Select all
from matplotlib import pyplot as plt
import matplotlib as mpl
import numpy as np
from netCDF4 import Dataset
# Read in the Sea Surface Temperature Anomaly Dataset
ncin = Dataset('201210.ERSST.anomaly.nc', 'r')
sst = ncin.variables['sst'][:]
lons = ncin.variables['lon'][:]
lats = ncin.variables['lat'][:]
ncin.close()
sst = np.squeeze(sst)
# setup the plot
fig = plt.figure()
# create the first axes for the main plot
ax1 = fig.add_axes([0.1, 0.1, 0.75, 0.8])
# define the colormap
cmap = plt.cm.Reds
# extract all colors from the Reds map
cmaplist = [cmap(i) for i in range(cmap.N)]
# make the first color entry to be Blue
cmaplist[0] = (.0,.0,1.0,1.0)
# make the last color entry to be Black
cmaplist[cmap.N-1] = (.0,.0,.0,1.0)
# create the new map
cmap = cmap.from_list('My cmap', cmaplist, cmap.N)
# define the contour levels and normalize
clevels = [-2, -1, 0, 0.5, 1, 2, 3, 4]
norm = mpl.colors.BoundaryNorm(clevels, cmap.N)
# Create the filled contour plot
scat = ax1.contourf(lons, lats, sst, level=clevels, cmap=cmap, norm=norm, extend='both')
ax1.set_xlabel('Longitude', size=12)
ax1.set_ylabel('Latitude', size=12)
# create the second axes for the colorbar
ax2 = fig.add_axes([0.86, 0.1, 0.02, 0.8])
# create the colorbar
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm, extend='both', spacing='proportional', ticks=clevels, boundaries=clevels)
ax2.set_ylabel('SST Difference (K)', size=12)
plt.show()
Here is the generated contour plot:
User could also download the Docker image for this recipe from dockerhub, and run the recipe using jupyter nootbook:
https://hub.docker.com/r/podaacdatarecipes/colorbar_discrete/