In [1]:
import matplotlib
from matplotlib.pyplot import get_cmap, colorbar, legend
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

In [2]:
def create_figure(params):
    dpi = 96.
    width = int(params['width'])
    height = int(params['height'])
    fig = plt.figure(frameon=False, dpi=dpi, figsize=(width, height), facecolor=None, edgecolor=None)
    fig.set_alpha(0)
    fig.set_figwidth(width / dpi)
    fig.set_figheight(height / dpi)
    return fig

Vertical Gradiant


In [12]:
p = dict(cmin=30,
         cmax=300,
         width=25,
         height=500,
         colormap='jet',
         showlabel=True,
         units='degrees',
         showvalues=True,
         logscale=False)
fig = create_figure(p)
ax = fig.add_axes([0.05, 0.05, 1.0, 1.0])

if p['logscale'] is True:
    CNorm = matplotlib.colors.LogNorm(vmin=p['cmin'], vmax=p['cmax'], clip=False)
else:
    CNorm = matplotlib.colors.Normalize(vmin=p['cmin'], vmax=p['cmax'], clip=False)
    
cb = matplotlib.colorbar.ColorbarBase(ax, cmap=get_cmap(p['colormap']), norm=CNorm, orientation='vertical')
if p['showvalues'] is False:
    cb.set_ticks([])
else:
    if p['logscale']:
        ticks = np.linspace(p['cmin'], p['cmax'], 5)
        cb.set_ticks(ticks)
        cb.set_ticklabels(ticks)
if p['showlabel']:
    cb.set_label(p['units'])


Horizontal Gradiant


In [13]:
p = dict(cmin=30,
         cmax=300,
         width=500,
         height=25,
         colormap='jet',
         showlabel=True,
         units='degrees',
         showvalues=True,
         logscale=False)
fig = create_figure(p)
ax = fig.add_axes([0.05, 0.05, 1.0, 1.0])

if p['logscale'] is True:
    CNorm = matplotlib.colors.LogNorm(vmin=p['cmin'], vmax=p['cmax'], clip=False)
else:
    CNorm = matplotlib.colors.Normalize(vmin=p['cmin'], vmax=p['cmax'], clip=False)

cb = matplotlib.colorbar.ColorbarBase(ax, cmap=get_cmap(p['colormap']), norm=CNorm, orientation='horizontal')

if p['showvalues'] is False:
    cb.set_ticks([])
else:
    if p['logscale']:
        ticks = np.linspace(p['cmin'], p['cmax'], 5)
        cb.set_ticks(ticks)
        cb.set_ticklabels(ticks)
if p['showlabel']:
    cb.set_label(p['units'])


Vertical Contours


In [66]:
p = dict(cmin=30,
         cmax=300,
         width=50,
         height=500,
         colormap='jet',
         showlabel=True,
         units='degrees',
         showvalues=True,
         logscale=False,
         numcontours=10)
fig = create_figure(p)
ax = fig.add_axes([0.05, 0.05, 1.0, 1.0])

if p['logscale'] is True:
    CNorm = matplotlib.colors.LogNorm(vmin=p['cmin'], vmax=p['cmax'], clip=False)
else:
    CNorm = matplotlib.colors.Normalize(vmin=p['cmin'], vmax=p['cmax'], clip=False)

levs = np.linspace(p['cmin'], p['cmax'], p['numcontours'])

x, y = np.meshgrid(np.ones(2), np.ones(2))
cs = ax.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(p['colormap']), extend='both')

cb = colorbar(mappable=cs, cax=ax, orientation='vertical', spacing='proportional', extendrect=False)

if p['showvalues'] is False:
    cb.set_ticks([])
else:
    cb.set_ticks(levs)
    cb.set_ticklabels(levs)
        
if p['showlabel']:
    cb.set_label(p['units'])


Vertical Contours (logscale)


In [67]:
p = dict(cmin=30,
         cmax=300,
         width=50,
         height=500,
         colormap='jet',
         showlabel=True,
         units='degrees',
         showvalues=True,
         logscale=True,
         numcontours=10)
fig = create_figure(p)
ax = fig.add_axes([0.05, 0.05, 1.0, 1.0])

if p['logscale'] is True:
    CNorm = matplotlib.colors.LogNorm(vmin=p['cmin'], vmax=p['cmax'], clip=False)
else:
    CNorm = matplotlib.colors.Normalize(vmin=p['cmin'], vmax=p['cmax'], clip=False)

levs = np.hstack(([p['cmin']-3], np.linspace(p['cmin'], p['cmax'], p['numcontours']), [p['cmax']+40]))

x, y = np.meshgrid(np.ones(2), np.ones(2))
cs = ax.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(p['colormap']))

cb = colorbar(mappable=cs, cax=ax, orientation='vertical', spacing='proportional', extendrect=False)

if p['showvalues'] is False:
    cb.set_ticks([])
else:
    cb.set_ticks(levs[1:-1])
    cb.set_ticklabels(levs[1:-1])
        
if p['showlabel']:
    cb.set_label(p['units'])


Horizontal Contours


In [70]:
p = dict(cmin=30,
         cmax=300,
         width=500,
         height=50,
         colormap='jet',
         showlabel=True,
         units='degrees',
         showvalues=True,
         logscale=False,
         numcontours=10)
fig = create_figure(p)
ax = fig.add_axes([0.05, 0.05, 1.0, 1.0])

if p['logscale'] is True:
    CNorm = matplotlib.colors.LogNorm(vmin=p['cmin'], vmax=p['cmax'], clip=False)
else:
    CNorm = matplotlib.colors.Normalize(vmin=p['cmin'], vmax=p['cmax'], clip=False)

levs = np.linspace(p['cmin'], p['cmax'], p['numcontours'])

x, y = np.meshgrid(np.ones(2), np.ones(2))
cs = ax.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(p['colormap']), extend='both')

cb = colorbar(mappable=cs, values=levs, cax=ax, orientation='horizontal', spacing='proportional', extendrect=False)

if p['showvalues'] is False:
    cb.set_ticks([])
else:
    cb.set_ticks(levs)
    cb.set_ticklabels(levs)
        
if p['showlabel']:
    cb.set_label(p['units'])


Horizontal Contours (logscale)


In [73]:
p = dict(cmin=30,
         cmax=300,
         width=500,
         height=50,
         colormap='jet',
         showlabel=True,
         units='degrees',
         showvalues=True,
         logscale=True,
         numcontours=10)
fig = create_figure(p)
ax = fig.add_axes([0.05, 0.05, 1.0, 1.0])

if p['logscale'] is True:
    CNorm = matplotlib.colors.LogNorm(vmin=p['cmin'], vmax=p['cmax'], clip=False)
else:
    CNorm = matplotlib.colors.Normalize(vmin=p['cmin'], vmax=p['cmax'], clip=False)

levs = np.hstack(([p['cmin']-3], np.linspace(p['cmin'], p['cmax'], 10), [p['cmax']+40]))

x, y = np.meshgrid(np.ones(2), np.ones(2))
cs = ax.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(p['colormap']))

cb = colorbar(mappable=cs, cax=ax, orientation='horizontal', spacing='proportional', extendrect=True)

if p['showvalues'] is False:
    cb.set_ticks([])
else:
    cb.set_ticks(levs[1:-1])
    cb.set_ticklabels(levs[1:-1])

if p['showlabel']:
    cb.set_label(p['units'])


Box Contours (filledcontours?)


In [75]:
p = dict(cmin=30,
         cmax=300,
         width=50,
         height=50,
         colormap='jet',
         showlabel=True,
         units='degrees',
         showvalues=True,
         logscale=False,
         numcontours=10)
fig = create_figure(p)
ax = fig.add_axes([0.05, 0.05, 1.0, 1.0])
ax.set_axis_off()

if p['logscale'] is True:
    CNorm = matplotlib.colors.LogNorm(vmin=p['cmin'], vmax=p['cmax'], clip=False)
else:
    CNorm = matplotlib.colors.Normalize(vmin=p['cmin'], vmax=p['cmax'], clip=False)

levs = np.linspace(p['cmin'], p['cmax'], p['numcontours'])

if p['showvalues'] is True:
    levs_labels = [str(x) for x in levs ]
    levs_labels[0] = "< " + str(p['cmin'])
    levs_labels[-1] = "> " + str(p['cmax'])
else:
    levs_labels = [ '' for x in range(levs.size) ]

x, y = np.meshgrid(np.arange(2), np.arange(2))
cs = ax.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(p['colormap']), extend='max')

proxy = [plt.Rectangle((0, 0), 0, 0, fc=pc.get_facecolor()[0]) for pc in cs.collections]

cb = legend(proxy, levs_labels, frameon=False)
if p['showlabel']:
    cb.set_title(p['units'])


Box Contours (not filledcontours?)


In [11]:
p = dict(cmin=30,
         cmax=300,
         width=50,
         height=50,
         colormap='jet',
         showlabel=True,
         units='degrees',
         showvalues=True,
         logscale=False,
         numcontours=10)
fig = create_figure(p)
ax = fig.add_axes([0.05, 0.05, 1.0, 1.0])
ax.set_axis_off()

if p['logscale'] is True:
    CNorm = matplotlib.colors.LogNorm(vmin=p['cmin'], vmax=p['cmax'], clip=False)
else:
    CNorm = matplotlib.colors.Normalize(vmin=p['cmin'], vmax=p['cmax'], clip=False)

levs = np.linspace(p['cmin'], p['cmax'], p['numcontours'])
levs_labels = levs
if p['showvalues'] is False:
    levs_labels = [ '' for x in range(levs.size) ]

x, y = np.meshgrid(np.ones(2), np.ones(2))
cs = ax.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(p['colormap']), extend='max')

proxy = [plt.Rectangle((0, 0), 0, 0, fc=pc.get_facecolor()[0]) for pc in cs.collections]

cb = legend(proxy, levs_labels, frameon=False)
if p['showlabel']:
    cb.set_title(p['units'])


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-dac48fc2f241> in <module>()
     24 
     25 x, y = np.meshgrid(np.arange(1), np.arange(1))
---> 26 cs = ax.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(p['colormap']), extend='max')
     27 
     28 proxy = [plt.Rectangle((0, 0), 0, 0, fc=pc.get_facecolor()[0]) for pc in cs.collections]

/data/conda/miniconda3-py36/envs/sciwms36/lib/python3.6/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
   1853                         "the Matplotlib list!)" % (label_namer, func.__name__),
   1854                         RuntimeWarning, stacklevel=2)
-> 1855             return func(ax, *args, **kwargs)
   1856 
   1857         inner.__doc__ = _add_data_doc(inner.__doc__,

/data/conda/miniconda3-py36/envs/sciwms36/lib/python3.6/site-packages/matplotlib/axes/_axes.py in contourf(self, *args, **kwargs)
   6179             self.cla()
   6180         kwargs['filled'] = True
-> 6181         contours = mcontour.QuadContourSet(self, *args, **kwargs)
   6182         self.autoscale_view()
   6183         return contours

/data/conda/miniconda3-py36/envs/sciwms36/lib/python3.6/site-packages/matplotlib/contour.py in __init__(self, ax, *args, **kwargs)
    844         self._transform = kwargs.pop('transform', None)
    845 
--> 846         kwargs = self._process_args(*args, **kwargs)
    847         self._process_levels()
    848 

/data/conda/miniconda3-py36/envs/sciwms36/lib/python3.6/site-packages/matplotlib/contour.py in _process_args(self, *args, **kwargs)
   1414                 self._corner_mask = mpl.rcParams['contour.corner_mask']
   1415 
-> 1416             x, y, z = self._contour_args(args, kwargs)
   1417 
   1418             _mask = ma.getmask(z)

/data/conda/miniconda3-py36/envs/sciwms36/lib/python3.6/site-packages/matplotlib/contour.py in _contour_args(self, args, kwargs)
   1472             args = args[1:]
   1473         elif Nargs <= 4:
-> 1474             x, y, z = self._check_xyz(args[:3], kwargs)
   1475             args = args[3:]
   1476         else:

/data/conda/miniconda3-py36/envs/sciwms36/lib/python3.6/site-packages/matplotlib/contour.py in _check_xyz(self, args, kwargs)
   1508             raise TypeError("Input z must be a 2D array.")
   1509         elif z.shape[0] < 2 or z.shape[1] < 2:
-> 1510             raise TypeError("Input z must be at least a 2x2 array.")
   1511         else:
   1512             Ny, Nx = z.shape

TypeError: Input z must be at least a 2x2 array.

In [ ]: