Fanning Consulting Services (25K)

Adding a Colorbar

Suppose you wanted to add a horizontal color bar over the top of a contour plot. Here is one way to do it.

First, load some colors. Let's suppose you want 200 colors.

   LOADCT, 5, NCOLORS=200
   ncolors = 200

Next, leave some space at the top of your contour plot for the color bar with the POSITION keyword. Like this:

   CONTOUR, DIST(31, 41), NLEVELS=25, $
      C_COLORS=INDGEN(25)*8, POSITION=[0.15, 0.15, 0.95, 0.8]

Now, suppose you want the color bar to be the length of the contour plot, and positioned above it. You might specify its location like this:

   loc = [0.15, 0.80, 0.95, 0.90]

I like to position my color bars in the graphics window with normalized coordinates, so that they go into any sized window. (Most of my graphics windows are resizeable these days.)

Now create a color bar. (For a vertical bar exchange the two expressions on either side of the matrix multiplier.)

   bar = BINDGEN(256) # REPLICATE(1B, 10)

Size the color bar for the current graphics window and get its starting location.

   xsize = (loc(2) - loc(0)) * !D.X_VSIZE
   ysize = (loc(3) - loc(1)) * !D.Y_VSIZE 
   xstart = loc(0) * !D.X_VSIZE
   ystart = loc(1) * !D.Y_VSIZE 

Scale the color bar to the number of colors you are using.

   bar = BYTSCL(bar, TOP=ncolors-1)

Display the color bar in the window. This will be slightly different depending upon whether you are outputting to PostScript or not. My code usually looks like this,

   IF !D.NAME EQ 'PS' THEN $
      TV, bar, xstart, ystart, XSIZE=xsize, YSIZE=ysize ELSE $
      TV, CONGRID(bar, xsize, ysize), xstart, ystart

Draw a box around the bar.

   PLOTS, [loc(0), loc(0), loc(2), loc(2), loc(0)], $
       [loc(1), loc(3), loc(3), loc(1), loc(1)], /NORMAL

Now, you can add annotations to the bar as needed. Many people use XYOUTS. I like to use the PLOT command to label the color bar because this gives me tick marks, nice labels, etc. It's up to you.

Note that this is only one way to produce color bars in IDL. You will probably discover other code and ways if you poke around at the various IDL sites.

You can find a fancier version of a colorbar procedure in the Example IDL Programs section. The program is named COLORBAR. You can also look at the COLORBAR documentation or you can download the program now.

[Return to IDL Programming Tips]

Copyright © 1996 David W. Fanning
Last Updated 2 December 1996