Coyote's Guide to IDL Programming

Sizing Text Proportionally

QUESTION: I have a resizeable graphics window and I want a legend to take up a particular proportion of the window in the upper right-hand corner. How can I size the string variables in my legend so they are always the proper size in the window?

ANSWER: The best way to do this is to use the WIDTH and CHARSIZE keywords to the XYOUTS command to iteratively size a string until it approaches a specified target width. (See the programming tip Calculating a String's Size for more information on using these keywords.)

For example, given a particular string in the variable string, you might find the string's initial width (and put it into the output variable thisWidth like this:

   size = 1.0
   XYOUTS, 0.5, 0.5, ALIGN=0.5, string, WIDTH=thisWidth, $
      CHARSIZE=-size, /NORMAL

Suppose this initial width was larger than the desired target width (expressed in the variable targetWidth). Then the correct character size can be found in an iterative process in which you subtract a small amount from the character size in each step. For example, suppose you want the target width to be 30% of the current graphics window. Your code might look something like this:

   targetWidth = 0.3
   IF thisWidth GT targetWidth THEN BEGIN
         XYOUTS, 0.5, 0.5, ALIGN=0.5, string, WIDTH=thisWidth, $
           CHARSIZE=-size, /NORMAL
         size = size - 0.01
      ENDREP UNTIL thisWidth LE targetWidth

At the end of this process, the variable size holds the proper character size for the string.

This is the type of algorithm used in the function STR_SIZE. This function can be used to calculate and return the character size that a particular string must be set to if it wants to closely match a specified target width. For example, if you want the title of your plot to be sized so that it always occupies one-half of the current graphics window, you might write your code like this:

   PLOT, data, POSITION=[0.1, 0.1, 0.9, 0.8]
   thisCharSize = STR_SIZE("Wind Speed Verses Time", 0.5)
   XYOUTS, 0.5, 0.9, "Wind Speed Verses Time", /NORMAL, $
      ALIGN=0.5, CHARSIZE=thisCharSize

You can see an example of the code above in which the title is set to be 50% of the window size in the illustration below.

Picture of Plot with Title 50% of Display Width (74K)

[Return to IDL Programming Tips]