Thanks very much for the help. I have made some progress, but am still having difficulties.

I wrote a function called make_solid_cmap (see test program below) that takes a colormap name, a list of thresholds, and a list of colors as inputs, and produces and registers a solid-color colormap. In the test program, I attempt to create a solid-color colormap containing the colors red, yellow, green, and blue.

Problem #1: When I use this colormap (in another piece of code that's not shown), the result is a series of shades of gray.

Problem #2: The test program attempts to retrieve and display all registered colormaps, but the one that I created in the test program does not appear in the figure.

Phillip

### Start of code ###
from matplotlib import *
import matplotlib.pyplot as pyplot
from numpy import linspace, outer
from pylab import *


# Section 1: Define function for generating solid-color colormaps.

def make_solid_cmap(cmap_name, colors, thresholds=None):
"""Use list of colors (names or RGB tuples) and list of thresholds to create
  a solid-color colormap."""
  # name_to_rgb converts a color name (string) to an RGB 3-tuple:
  from webcolors import name_to_rgb

  print 'len(colors)= ', len(colors)

  if not isinstance(colors,list) or len(colors)<2:
     raise Exception, 'colors must be a list of length 2 or greater.'

  if thresholds is None:
     # Assign default set of uniformly-spaced thresholds:
     thresholds= linspace(0.0, 1.0, len(colors)+1)[1:-1]
  else:
     if not isinstance(thresholds,list):
        raise Exception, 'thresholds must be a list.'

  print 'thresholds= ', thresholds

  if not isinstance(cmap_name,str) or len(cmap_name)==0:
     raise Exception, 'cmap_name must be a non-null string.'
  if len(colors)!=len(thresholds)+1:
raise Exception, 'The list of colors must be one longer than the list ' \
       'of thresholds.'

  for i in range(len(colors)):
# If the ith color is specified via a name, replace the string with an RGB
     # 3-tuple:
     if isinstance(colors[i],str): colors[i]= name_to_rgb(colors[i])

     # If all three components of the tuple are ints, normalize by 256. to
     # obtain floats in [0,1):
     if isinstance(colors[i][0],int) and isinstance(colors[i][1],int) and \
        isinstance(colors[i][2],int):
colors[i]= (colors[i][0]/256., colors[i][1]/256., colors[i][2]/256.)

  # For each of the three RGB components, create initial empty list:
  red_list= green_list= blue_list= []

  # Each list will consist of a series of 3-tuples.  The components of each
# 3-tuple are the threshold value, y0, and y1. The threshold in the first
  # tuple is always zero, and the second component of the first tuple is
  # ignored, so we can set it to zero as well.

  red_list     .append( (0.0          , 0.0,           colors[0][0]  ) )
  green_list   .append( (0.0          , 0.0,           colors[0][1]  ) )
  blue_list    .append( (0.0          , 0.0,           colors[0][2]  ) )

  for i in range(len(thresholds)):
     red_list  .append( (thresholds[i], colors[i][0],  colors[i+1][0]) )
     green_list.append( (thresholds[i], colors[i][1],  colors[i+1][1]) )
     blue_list .append( (thresholds[i], colors[i][2],  colors[i+1][2]) )

  red_list     .append( (1.0          , colors[-1][0], 0.0           ) )
  green_list   .append( (1.0          , colors[-1][1], 0.0           ) )
  blue_list    .append( (1.0          , colors[-1][2], 0.0           ) )

  cmap= matplotlib.colors.LinearSegmentedColormap(cmap_name, {
    'red'  : tuple(red_list),
    'green': tuple(green_list),
    'blue' : tuple(blue_list)
  } )

  pyplot.register_cmap(cmap=cmap)


# Section 2: Create and register a solid-color colormap containing red, yellow,
# green, and blue (in that order):

make_solid_cmap('rygb', ['red','yellow','green','blue'])


# Section 3: Display all registered colormaps.

close(1)
rc('text', usetex=False)
a=outer(arange(0,1,0.01),ones(10))
fig= pyplot.figure(figsize=(13,7), dpi=120, facecolor=[1,1,1])
subplots_adjust(top=0.8,bottom=0.05,left=0.01,right=0.99)
maps=[m for m in cm.datad.keys() if not m.endswith("_r")]
maps.sort()
l=len(maps)+1
i=1
for m in maps:
   print m
   subplot(1,l,i)
   axis("off")
   imshow(a,aspect='auto',cmap=get_cmap(m),origin="lower")
   title(m,rotation=90,fontsize=18)
   i=i+1
show()


Eric Firing wrote:
Dr. Phillip M. Feldman wrote:
I'd like to be able to create and use a custom colormap. I'm creating the
colormap via
the following statement:

matplotlib.colors.ListedColormap([(0,0,0),(0.6,0,0),(0,0.6,0),(0.6,0.6,0)],
  name='Earth')

Assign it to a variable, like

earth_cmap = matplotlib.colors.ListedColormap(
   [(0,0,0),(0.6,0,0),(0,0.6,0),(0.6,0.6,0)],
   name='Earth')

and then use cmap=earth_cmap as your kwarg specification.

The ability to register user-generated cmaps so that they can be retrieved via get_cmap is very new, and not present in 0.98.5. It is in the latest release (0.99.1), though. You would need to use the register_cmap function.

Eric


The above statement appears to work, but when I attempt to use this
colormap, I
get the error shown below.  Any suggestions will be appreciated.

AssertionError Traceback (most recent call last)

art.py in <module>()
    253
    254 # Plot z as image using specified color map:
--> 255 pyplot.imshow(z, origin='lower', cmap=get_cmap(map_names[n_map-1]),
    256   extent=[x.min(),x.max(),y.min(),y.max()])
    257

C:\Program
Files\Python25\lib\site-packages\matplotlib-0.98.5.2n2-py2.5-win32.egg\matplotlib\cm.pyc
in get_cmap(name, lut)
     19     if lut is None: lut = mpl.rcParams['image.lut']
     20
---> 21     assert(name in datad.keys())
22 return colors.LinearSegmentedColormap(name, datad[name], lut)
     23

AssertionError:



------------------------------------------------------------------------------
Come build with us! The BlackBerry&reg; Developer Conference in SF, CA
is the only developer event you need to attend this year. Jumpstart your
developing skills, take BlackBerry mobile applications to market and stay 
ahead of the curve. Join us from November 9&#45;12, 2009. Register now&#33;
http://p.sf.net/sfu/devconf
_______________________________________________
Matplotlib-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-users

Reply via email to