We already used the brewer2mpl
module in previous posts. However, we did not showed it in detail. This post
is just to draw attention to this interesting module that can access the
Colorbrewer2.0 website and convert colormaps
directly to matplotlib format.
Let's start importing by cartopy
, iris
, pyplot
, and numpy
.
import numpy as np
import matplotlib.pyplot as plt
import iris
import iris.plot as iplt
import cartopy.crs as ccrs
import iris.quickplot as qplt
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
We will plot a topography map using the
etopo1 data from the NOAA opendap
server. With iris
we can slice the data before downloading the it. Finally
we will "print" our cube to check the metadata.
def get_cube(url):
coord_values = {'latitude':lambda cell: -25 <= cell <= -22,
'longitude': lambda cell: -46 <= cell <= -42}
constraint = iris.Constraint(coord_values=coord_values)
bathy = iris.load_cube(url, constraint)
return bathy
try:
bathy = get_cube('/home/filipe/00-NOBKP/OcFisData/ETOPO1_Bed_g_gmt4.grd')
except:
bathy = get_cube('http://www.ngdc.noaa.gov/thredds/dodsC/relief/ETOPO1/thredds/ETOPO1_Bed_g_gmt4.nc')
print(bathy)
Now we will use brewer2mpl
to create two color pallets, one with Greens
for land, and another with Blues for the ocean. We reversed the ocean
pallet because we want the darker blue at deeper depths. In addition, we will
cap the first two green levels to get a darker shade of green at the highest
heights. Finally, we concatenate both colors and convert them to matplotlib
values.
from brewer2mpl import brewer2mpl
land = brewer2mpl.get_map('Greens', 'sequential', 9)
ocean = brewer2mpl.get_map('Blues', 'sequential', 7, reverse=True)
colors = np.array(ocean.mpl_colors + land.mpl_colors[2:])
levels = [-4000, -2500, -1000, -700, -400, -145, -10, 0, 10, 145, 400, 800, 1200, 1600]
fig, ax = plt.subplots(figsize=(6, 6),
subplot_kw=dict(projection=ccrs.PlateCarree()))
qplt.contourf(bathy, levels, colors=colors, extend='both')
ax.coastlines('10m', color='k')
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=1.5, color='gray', alpha=0.5, linestyle='--')
gl.xlabels_top = False
gl.ylabels_right = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
iplt.citation('Inspired by\nhttp://nbviewer.ipython.org/5254237')
Much easier (and more readable) then the old
MatlabTM way
which still needs to perform an overlay of the subplots making the code look
even worse than with just the clim
trick!
HTML(html)