Fanning Software Consulting

Adding a Legend to a CGS Window

QUESTION: Can you show me an easy way to add a legend to a CGS graphics window in IDL?

ANSWER: Most IDL programmers add legends to their graphics displays with the NASA IDL Astronomy Library program AL_Legend. This program was previously named Legend, but had to be renamed when IDL 8 confiscated the name for one of its IDL graphics functions. While the program was being renamed, it was modified to use Coyote Graphics System (CGS) commands, making it extremely easy to use it with CGS graphics windows. IDL programers like AL_Legend because it has a great many features, is flexible, and is easy to use.

The following code, for example, creates a plot with two data sets and labels them with a legend in the upper left hand corner of the plot. The plot is created in a resizeable CGS window. The legend is added to the window by simply setting the Window keyword on the AL_Legend command.

   cgPlot, cgDemoData(17), PSym=-15, Color='red', YRange=[0,120], $
      LineStyle=0, YStyle=1, /Window
   cgPlot, cgDemoData(17), PSym=-16, Color='dodger blue', /Overplot, $
      LineStyle=2, /AddCmd
   al_Legend, ['Experiment 1', 'Experiment 2'], PSym=[-15,-16], $
      LineStyle=[0,2], Color=['red','dodger blue'], Position=[5,115], /Window

You see an example of what the code produces in the figure below.

CGS Plot with a legend.
A CGS IDL plot with a legend.
 

Note that if AL_Legend throws an error from Convert_Coord when you run this code, that you will need to either patch your version of AL_Legend or download a version created after 16 May 2011. If you decide to patch your version, you can add the following lines of code on or about line 400 in AL_Legend. This will be in case 2 of the CASE statement, just before the calls to Convert_Coord.

  ; if keyword "window" is set, then set the current graphics window.
  if keyword_set(window) then begin
     wid = cgQuery(/current)
     wset, wid
  endif

Version of IDL used to prepare this article: IDL 7.0.1.

Last Updated: 16 May 2011