matplotlib Colormaps Using custom colormaps


Apart from the built-in colormaps defined in the colormaps reference (and their reversed maps, with '_r' appended to their name), custom colormaps can also be defined. The key is the module.

The below example defines a very simple colormap using cm.register_cmap, containing a single colour, with the opacity (alpha value) of the colour interpolating between fully opaque and fully transparent in the data range. Note that the important lines from the point of view of the colormap are the import of cm, the call to register_cmap, and the passing of the colormap to plot_surface.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import as cm

# generate data for sphere
from numpy import pi,meshgrid,linspace,sin,cos
th,ph = meshgrid(linspace(0,pi,25),linspace(0,2*pi,51))
x,y,z = sin(th)*cos(ph),sin(th)*sin(ph),cos(th)

# define custom colormap with fixed colour and alpha gradient
# use simple linear interpolation in the entire scale
                 data={'red':   [(0.,0,0),

                       'green': [(0.,0.6,0.6),

                       'blue':  [(0.,0.4,0.4),

                       'alpha': [(0.,1,1),

# plot sphere with custom colormap; constrain mapping to between |z|=0.7 for enhanced effect
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

example with alpha gradient

In more complicated scenarios, one can define a list of R/G/B(/A) values into which matplotlib interpolates linearly in order to determine the colours used in the corresponding plots.