coyote traduction

41
IDL Programming Techniaues I Second Edition -- David W; Fanlzing, Ph.D.

Upload: diego-tk

Post on 30-Nov-2015

153 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: Coyote Traduction

IDL Programming Techniaues

I

Second Edition

-- David W; Fanlzing, Ph.D.

Page 2: Coyote Traduction

Simple Graphical Displays

Chapter Overview The bread and butter of scientific analysis is the ability to see your data as simple line plots, contour plots and surface plots. In this chapter, you will learn how easy it is to display your data this way. You will also learn to use system variables and keywords to position and annotate simple graphical displays.

Specifically, you will learn:

Q How to display data as a line plot with the Plot command

* How to display data as a surface with the Sulfice and Sl~ade-Su~fcommands

How to display data as a contour plot with the Corztour

command

Q How to position simple graphical displays in the

display window

* How to use common keywords to annotate and customize your

graphical displays

Simple Graphical Displays in IDL A simple graphical display in IDL is an example of what is called a

raster graphic.

That is to say, using a Plot, or C01~tozll; or Szlgace command generates

an algorithm

that lights up certain pixels in the display window.

Such raster graphics have no

persistence. In other words, once IDL has displayed

the graphic and lighted up certain

pixels it has no knowledge of what it has done. This means, for

example, that IDL has

no way to respond to the user resizing the display window. The

graphics display

cannot, in general, be redrawn in such circumstances except by

re-issuing the graphics

command over again.

Nevertheless, raster graphics commands are widely used in IDL

because they are fast

and simple to use. And, as you will see, many of the limitations often

associated with

raster graphic commands can be overcome if you are careful in how

you write IDL

programs that use raster graphic commands. This chapter introduces

you to the

concepts you will need to know to wi-ite resizeable

IDL graphics windows or produce

hardcopy output directly with raster graphic commands.

The graphics commands in

this chapter are concerned with what Research Systems calls direct

graplzics.

A different type of graphics option-named object graplzics by Research Systems- was introduced in IDL 5.0. Object graphics commands are considerably harder to use, but they also give you more power and flexibility in how your IDL graphic programs

Descubriendo las Posibilidades

Visualizar Gráficos SimplesResumen del capítulo

El pan y la mantequilla del análisis científico es la capacidad de ver los datos como simple trasos de línea ,contorno y superficie. En este capítulo, usted aprenderá lo fácil que es mostrar los datos de esta manera.También aprenderá a utilizar las variables de sistema y palabras clave para posicionar y visualizargraficos simples en pantallas.Específicamente, usted aprenderá:•ÿCómo mostrar los datos como un gráfico de líneas con el comando Plot•ÿCómo mostrar los datos como una superficie con los comandos Surface y Shade_Surface•ÿCómo mostrar los datos como un gráfico de contorno con el comando Contour•ÿCómo colocar pantallas gráficas simples en la pantalla•ÿCómo utilizar palabras clave más comunes para anotar y personalizar sus pantallas gráficas

Pantallas gráficas simples en IDLUna pantalla gráfica sencilla en IDL es un ejemplo de lo que se llama un gráfico raster.

Es decir, el uso de un gráfico, o contorno, o el comando de superficie genera un algoritmoque ilumina algunos píxeles en la ventana de visualización. Tales gráficos de trama no tienenpersistencia. En otras palabras, una vez IDL ha mostrado el gráfico y alumbrado ciertapíxeles que no tiene conocimiento de lo que ha hecho. Esto significa, por ejemplo, que tiene IDLno hay manera de responder a el cambio de tamaño de la ventana de visualización del usuario. La pantalla gráfica no puede, en general, ser dibujada en tales circunstancias sino por volver ala emisión de los gráficos ordenar otra vez.Sin embargo, los comandos de gráficos de trama son ampliamente utilizados en IDL porque sonrápidos y fácil de usar. Y, como se verá, muchas de las limitaciones a menudo asociada concomandos gráficos de trama se pueden superar si se tiene cuidado en la forma de escribirprogramas en IDL que utilizan comandos gráficos raster. Este capítulo es una introducción a laconceptos que se necesita saber para mostrar ventanas gráficas IDL o producir salida de copiaimpresa directamente con comandos gráficos de trama. Los comandos de gráficos enEste capítulo se ocupa de lo Systems Research llamadas direct graphics.Un tipo diferente de opción gráfica de nombre object graplzics de Research System fueintroducido en IDL 5.0. Comandos gráficos de objetos son mucho más difícil de usar,pero también le dan más poder y flexibilidad en cómo los programas gráficos IDLlínea de comandos. Más bien, se incluyen en los programas de IDL, especialmente widget deprogramas (programas con interfaces gráficas de usuario). Comandos gráficos de objetos sondiscutido más adelante en este libro.

Page 3: Coyote Traduction

Sii~~ple Grnplzical Displays

are written. Object graphics comnlands are not really meant to be typed at the IDL command line. Rather, they are included in IDL programs, especially widget programs (programs with graphical user interfaces). Object graphics commands are discussed later in this book.

Creating Line Plots The simplest way to generate a line plot is to plot a vector. You can use the LoadDatcr command to open the Tilne Series Data data set. The LoaclDnta command is one of the IDL programs that came with this book. (See "IDL Programs and Data Files Used in the Book" on page 4 for more information.) It is used to load the data sets used in the programming examples in this book. To see the data sets available to you, type

this: IDL> curve = ~ o a d ~ a t a o

If you forgot to include the parentheses when you issued the LoadData command above, you may need to re-compile the LoadData program before it will work prop- erly. The reason for this is that IDL now thinks "loaddata" is a variable and acts accordingly when it sees it in a command line. Re-compiling the function will get the "loaddata" name on IDL's list of function names where it belongs. Type this:

IDL> . Compile LoadData The Tilne Series Data data set is the first data set on the LoadData list. Click on it. The data is now loaded into the variable cul-ve. Another way to select this first data set is to call LoadData like this:

IDL> curve = LoadData (1)

To see how the variable curve is defined, type this:

IDL> Help, curve

CURVE FLOAT = Array [loll

You see that cuive is a floating point vector (or one-dimensional array) of 101 elements.

To plot the vector, type:

IDL> Plot, curve

IDL will try to plot as nice a plot as it possibly can with as little information as it has. In this case, the X or horizontal axis is labeled from 0 to 100, corresponding to the number of elements in the vector, and the Y or vertical axis is labeled with data coordinates (i.e., this is the dependent data axis).

But most of the time a line plot displays one data set (the independent data) plotted against a second data set (the dependent data). For example, the curve above may represent a signal that was collected over some period of time. You might want to plot the value of the signal at some moment of time. In that case, you need a vector the same length as the curve vector (so you can have a one-to-one correspondence) and scaled into the units of time for the experiment. For example, you can create a time vector and plot it against the curve vector, like this:

IDL> time = FIndGen(lO1) * (6.0/100) IDL> Plot, time, curve

The FIlzdGerz command creates a vector of 101 elements going from 0 to 100. The multiplication factor scales each element so that the final result is a vector of 101 elements going from 0 to 6. Your graphical output should look similar to that in Figure 1.

Creación de gráficos de líneaLa forma más sencilla de generar un gráfico de líneas es trazar un vector. Usted puede utilizarel comando LoadData para abrir los datos serie deTiempos. El comando LoadData es uno delos programas de IDL que vienen con este libro. (Ver "IDL programas y archivos de datos utilizadosen el libro "en la página 4 para obtener más información.) Se utiliza para cargar los conjuntos de datosutilizados en los ejemplos de programación de este libro. Para ver los conjuntos de datos a su disposición, el tipee esto:

Si usted se olvidó de incluir los paréntesis cuando se ha emitido el mandato LoadDataanteriormente, es posible que tenga que volver a compilar el programa LoadData antesde que funcione correctamente. La razón de esto es que IDL ahora piensa "loaddata" es una variable y actua en consecuencia cuando lo ve en una línea de comandos. Vuelva a compilar la función de Nombre "loaddata" en la lista de los nombres delas funciones que le corresponde a IDL. Escriba lo siguiente:

Los Datos en serie de tiempo son el primer conjunto de datos en la lista LoadData. Haga clic en él. Losdatos ya está cargados en la variable curve. Otra manera para seleccionar este primer conjunto dedatos es llamar a LoadData así:

Para ver cómo se define la variable curve, escriba lo siguiente:

Usted ve que la curva es un vector de punto flotante (o matriz unidimensional) de 101 elementos.Para trazar el vector, escriba:

IDL intentará trazar tan bien una linea como sea posible con la menor cantidad de información que tiene.En este caso, el eje X u horizontal está marcada de 0 a 100, correspondiente a la número de elementosen el vector, y el eje Y o vertical se etiqueta con los datos coordenadas (es decir, este es el eje de datosdependiente).Pero la mayoría de las veces un gráfico de líneas muestra un conjunto de datos (los datos independientes)representados en contra de un segundo conjunto de datos (los datos dependientes). Por ejemplo, la curvaanterior puede representa una señal que se recogió sobre un cierto período de tiempo. Es posible que desee trazar el valor de la señal en algún momento de tiempo. En ese caso, se necesita un vector de lamisma longitud que el vector curve (por lo que puede tener uno-a-uno) y una escala en las unidadesde tiempo para el experimento. Por ejemplo, puede crear un vector tiempo y plotearlo contra el vectorcurve, así:

El comando FIndGen crea un vector de 101 elementos que van de 0 a 100. La escala del factor demultiplicación para cada elemento de manera que el resultado final es un vector de 101 elementos que van de 0 a 6. Su salida gráfica debe ser similar a la de Figura 1.

Page 4: Coyote Traduction

Creating Line Plots

Figure I : A plot of the independent data (time) versus the dependent data (curve).

Notice that there are no titles on the axes associated with this plot. Placing titles on graphics plots is easy. Just use the XTitle and YTitle keywords. For example, to label the curve plot, you can type this:

IDL> Plot, time, curve, XTitle=ITime Axis1, $ YTitle=ISignal Strength1

You can even put a title on the entire plot by using the Title keyword, like this:

JDL> Plot, time, curve, XTitle='Time Axis1, $ YTitle=lSignal Strength1, Title=lExperiment 35M1

Your output will look similar to the illustration in Figure 2. Note that the display shows white lines on a black background, while the illustration shows black lines on a white background. These illustrations are encapsulated Postscript files produced by IDL. It is common for the drawing and background colors to be reversed in PostScript files. (See "Problem: PostScript Devices Use Background and Plotting Colors Differently" on page 189 for more information.)

Experiment 35M 30

5 m E 20 G - g 10 m iTj

0 0 2 4 6

Time Axis

Figure 2: A simple line plot with axes labels and a plot title.

Figura I: una grafica de los datos independientes (tiempo) versus los datos de dependiente (curve).

Tenga en cuenta que no hay títulos en los ejes asociados con esta trama. La colocación de títulos enventana de gráficos es fácil. Sólo tiene que utilizar las palabras claves XTitle e YTitle. Por ejemplo, para etiquetar la trama curve, puede escribir lo siguiente:

Usted puede incluso poner un título en toda la parcela con la palabra clave Title, así:

Su salida será similar a la ilustración en la Figura 2. Tenga en cuenta que la pantalla muestra líneasblancas sobre un fondo negro, mientras que la ilustración muestra las líneas negras sobre unel fondo blanco. Estas ilustraciones se encapsulan archivos PostScript producidos por IDL.Es común que el dibujo y los colores de fondo se invierta en el archivos PostScript. (Consulte lasección "Problema: Los dispositivos PostScript uso de fondo y el trazado Colores Diferente "en lapágina 189 para obtener más información.)

Figura 2: una simple línea ploteada con ejes etiquetados y un título

Page 5: Coyote Traduction

Si~nple Graphical Displays

Notice that the plot title is slightly larger than the axes labels. In fact, it is 1.25 times as large. You can change the size of all the plot annotations with the Charsize keyword. For example, if your eyes are like mine, you might want to make the axis characters about 50% larger, like this:

IDL> Plot, time, curve, XTitle=ITime Axis', $ YTitle='Signal Strength1, Title=l~xperiment 35M1, $ CharSize=1.5

If you want the character size on all your graphic displays to be larger than normal, you can set the ChnrSize field on the plotting system variable, like this:

IDL> ! P. CharSize = 1.5

Now all subsequent graphics plots will have larger characters, unless specifically overruled by the ChnrSize keyword on a graphics output command.

You can even change the character size of each individual axis by using the [XYZIChnrSize keyword. For example, if you want the Y axis annotation to be twice the size of the X axis annotation, you can type this:

IDL> Plot, time, curve, XTitle='Time Axis', XCharSize=l.O, $ YTitle=lSignal Strength', YCharSize=2.0

Note that the [XYZIChnrSize keywords use the current character size as the base from which they calculate their own sizes. The current character size is always stored in the system variable !l? CharSize. This means that if you set the XCharSize keyword to 2 when the !RCharSize system variable is also set to 2, then the characters will be four times their normal size.

Customizing Graphics Plots

This is a simple line plot, without much information associated with it, aside from the data itself. But there are many ways to customize and annotate line plots. The Plot command can

be modified with over 50 different keywords. Here are a few of the

things you might want

to do:

modify line styles or thicknesses

use symbols with or without lines between them

create your own plotting symbols

add color in your plot to highlight important features

change the length of tick marks or the number of tick intervals

use logarithmic scaling on the plot axes

change the data range to plot just the subset of the data you are interested in

eliminate axes or otherwise change the style of the plot

Modifying Line Styles

and Thicknesses Suppose, for example, you wanted to plot your data with different line styles. For a line with a long dash line style, you can try this:

IDL> Plot, time, curve, LineStyle=5

Different line styles are selected for line plots by using the LirzeStyle keyword with one of the index numbers shown in Table 3. For example, if you wished to plot the curve with dashed line, you set the Linestyle keyword to a value of 2, like this:

IDL> Plot, time, curve, LineStyle=2

Tenga en cuenta que el título de la trama es un poco mayor que las etiquetas de los ejes. De hecho,es 1,25 veces tan grande. Usted puede cambiar el tamaño de todas las anotaciones de la trama conla palabra clave CharSize. Por ejemplo, si tus ojos son como el mío, es posible que desee que el ejede caracteres sea aproximadamente 50% más grandes, como este:

Si desea que el tamaño de la fuente de todas las pantallas gráficas sea más grande de lo normal,se puede establecer el campo CharSize en la variable de sistema trazado, así:

Ahora todas las parcelas gráficos posteriores tendrán caracteres más grandes, a menos quesea específicamente revocada con la palabra clave CharSize en un comando de salida de gráficos.Usted puede incluso cambiar el tamaño de los caracteres de cada eje individual mediante elPalabra clave [XYZ]CharSize. Por ejemplo, si desea que el eje anotación Y para ser dos vecesel tamaño del eje X de anotación, puede escribir lo siguiente:

Tenga en cuenta que las [palabras clave [XYZ]charSize utilizan el tamaño de la fuente actualcomo el punto de partida que calculan sus propios tamaños. El tamaño de la fuente de corrientesiempre se almacena en la variable del sistema ! P.CharSize. Esto significa que si se establecela palabra clave XCharSize a 2 cuando la variable del sistema !P.CharSize también se estableceen 2, a continuación, las fuentes serán cuatro veces su tamaño normal.

Personalizando los trazos de la gráficaEste es un simple gráfico de líneas, sin mucha información asociada con él, además de los datos en sí.Pero hay muchas maneras de personalizar y anotar trazos de línea. El comando plot se puede modificarcon más de 50 palabras claves diferentes. Éstos son algunos de las cosas que usted puede hacer:

modificar los estilos de línea y grosores

utilizar símbolos con o sin líneas entre ellos

crear sus propios símbolos trazado

añadir color en su parcela para resaltar características importantes

cambiar la longitud de las marcas o el número de intervalos

utilizar la escala logarítmica en los ejes de la trama

cambiar el rango de datos para trazar sólo el subconjunto de los datos que usted está interesado

eliminar los ejes o de otra manera cambiar el estilo de la trama

Modificación de estilos de línea y grosoresSupongamos, por ejemplo, que quería trazar sus datos con diferentes estilos de línea. Para una

línea con mucho estilo línea de trazos, puede intentar lo siguiente:

Diferentes estilos de línea son seleccionados por trazos de línea mediante el uso de la palabraclave LineStyle uno de los números índices se muestran en la Tabla 3. Por ejemplo, si usted desea trazar la curva con línea discontinua, se encuentra la palabra clave lineStyle a un valorde 2, así:

Page 6: Coyote Traduction

Cztstontiziirg Grcrplzics Plots

Table 3: The line style carz be clta~zged by assignirzg these index nz~~nbers to the Linestyle keyword.

The thickness of lines used on line plots can also be changed. For example, if you wanted the plot displayed with dashed lines that were three times thicker than normal you can type this:

IDL> Plot, time, curve, LineStyle=2, Thick=3

Displaying Data with Symbols Instead of Lines Suppose you wanted to plot your data with symbols instead of lines. Like the Linestyle keyword, similar index numbers exist to allow you to choose different symbols for your line plots. Table 4 shows you the possible index numbers you can use with the PSyni (Plotting Syr?ibol) keyword. For example, you can draw the plot with asterisks by setting the PSyr?z keyword to 2, like this:

IDL> Plot, time, curve, PSym=2

Your output should look similar to the output in Figure 3.

Figure 3: A line plot with the data plotted as symbols instead of as a line.

Displaying Data with Lines and Symbols You can connect your plot symbols with lines by using a negative value for the PSym keyword. For example, to plot your data with triangles connected by a solid line, type

DL> Plot, time, curve, P S p = - 5

Mostrar datos con símbolos en lugar de las líneasSupon que quieres delinear tus datos con símbolos en lugar de las líneas. Con la palabra Linestyle(estilo de líneas), similar al índice de números que existe nos permitirle escoger los símbolos diferentes para tu línea de trazo. La tabla 4 le muestra los números posibles de índice que usted puede usar con la palabra PSym ( Plotting Symbol ) . ¿Por ejemplo, puede dibujar una línea de asteriscos poniendo la palabra PSym igual a 2, así:

su salida debe ser similar a la salida en la figura 3.

Figura 3: Un trazo de línea con los datos delineados como símbolos en lugar de como una línea.

Mostrando datos con líneas y símbolos

Puede unir sus símbolos con líneas usando un valor negativo para la palabra PSym.Por ejemplo, para delinear sus datos con triángulos unidos por una línea llena, teclee

El grosor de las líneas utilizadas en parcelas de línea también se puede cambiar. Por ejemplo, si ustedquería que la trama se muestra con líneas discontinuas que eran tres veces más gruesa de lo normalpuede escribir lo siguiente:

Tabla 3: El estilo de línea se puede cambiar asignando estos números de índicepara la palabra clave LineStyle.

número índice estilo de línea

sólido

puntadas

guiones

punto y guiones

guion punto punto

guiones largos

Page 7: Coyote Traduction

Siirtple Graphical Displays

To create larger symbols, add the SyrlzSize keyword like this. Here the symbol is twice the "normal" size. A value of 4 would make the symbol four times its normal size, and SO on.

IDL> Plot, time, curve, PSym=-5, ~ym~ize=2.0

Table 4: Tlzese are the index izuntbers you can ztse witlt tlze PSym keyword to produce different plotting symbols on your plots. Note that using a negative number for the plotting symbol will coizrtect the symbols with lines.

4

5

6

7

8

9

10

-PSyn?

Diamond

Tiiangle

Square

X

User defined (with the UserSyn? procedure).

This index is not used for anything!

Data is plotted in histogram mode.

Negative values of PSYIII connect symbols with lines.

If you feel creative, you can even create your own plotting symbols. The Usedyn? command is used for this purpose. After you have created your special symbol, you select it by setting the PSym keyword equal to 8. Here is an example that creates an star as a symbol. The vectors x and y define the vertices of the star as offsets from the origin at (0,O). You can create a filled symbol by setting the Fill keyword on the UserSyrn command.

IDL> X = [O.O, 0.5, -0.8, 0.8, -0.5, 0.01 IDL> y = [1.0, -0.8, 0.3, 0.3, -0.8, 1.01 IDL> TvLCT, 255, 255, 0, 150 IDL> UserSym, X, y, Color=150, /Fill IDL> Device, Decomposed=O IDL> Plot, time, curve, PSym=-8, SymSize=2.0

Your output should look similar to the output in Figure 4.

Drawing Line Plots in Color You can draw your line plots in different colors. (Colors are discussed in detail in "Working with Colors in IDL" on page 81. For now, just type the TvLCT command below. You will learn exactly what the command means later. Basically, you are loading three color vectors that describe the red, green, and blue components of the

Creando su propio dibujo símbolico

Para crear los símbolos más grandes, añada la palabra SymSize . Aquí el símbolo es dos veces el "tamaño normal". Un valor de 4 harían el símbolo cuatro veces su tamaño normal, y así susesivamente.

TABLA 4:Éstos son los números de índice que usted puede usar con la palabra clave de PSym para producirdiferentes símbolos. Nota usando un número negativo para PSym, unirá los símbolos con las líneas.

Si se siente creativo, puede aún crear sus propios dibujos símbolicos. El comando UserSymes usada para este propósito. Después que ha creado su símbolo especial, usted lo escogeponiendo la palabra PSym igual a 8. Aquí está un ejemplo que crea una estrella como un símbolo. El vector (x, y) define los vertices de la estrella como compensaciones del origen a (0,0). Nosotros podemos crear un símbolo lleno poniendo la palabra Fill en la orden de UserSyrn.

Su salida deba parecer similar a la salida en la figura 4.

Hacer las línea de dibujo en color

Puede dibujar sus línea en colores diferentes. ( los colores se discuten en detalle " trabajando con colores en IDL " en la página 81. Por ahora, sólo represente la ordenTvLCT abajo. Estudiará exactamente lo que el comando significa más tarde. Básicamente, está cargando 3 vectores de colores que describen los componentes rojos, verdes, y azules de el

índice de Número el uso de símbolos de dibujos

Ningún símbolo es usado y los puntos se unen por líneas.

Signo más

Asterisco

Período

Diamante

Triángulo

Cuadrado

X

Definido por el usuario (con el procedimiento de UserSym).

este índice no se usa para algo !

Los datos se dibujan en el modo de histograma.

Los valores negativos de PSym une símbolos con las líneas.

Page 8: Coyote Traduction

Cztsto~?zizi~zg Gr~apltics Plots

Figzcre 4: A plot with syntbols created by the UsesSynt procedzcre.

color triples that describe the charcoal, yellow, and green colors.) For example, load a charcoal, yellow and green color into color indices 1,2, and 3 like this:

IDL> TVLCT, [70, 255, 01, [70, 255, 2551 I [70, 0, 01 I 1

To draw the plot in yellow on a charcoal background, type:

IDL> Plot, time, curve, Color=2, Background=l

If nothing appears in your display window when you type the command above, it is likely because you are running IDL on a 24-bit color display and you have color decomposition turned on. You will learn more about color decomposition later, but for now, be sure color decomposition is off. Type this to produce the proper colors:

IDL> Device, Decomposed=O IDL> Plot, time, curve, Color=2, Background=l

If you want just the line to be a different color, you must first plot the data with the

NoDntn keyword turned on, then overplot the line with the OPlot command (discussed below). For example, to have a yellow plot on a charcoal background, with the data in green, type:

IDL> Plot, time, curve, Color=2, Background=l , / ~ o ~ a t a IDL> OPlot , time, curve, Color=3

Limiting the Range of Line Plots Not all of your data must be plotted on a line plot. You can limit the amount of data you plot with keywords. For example, to plot just the data that falls between 2 and 4 on the X axis, type:

IDL> Plot, time, curve, XRange= [2,4]

Or, to plot just the portion of the data that has Y values between 10 and 20 and X values that fall between 2 and 4, type:

IDL> Plot, time, curve, ~ ~ a n g e = [10,20] , XRange= [2,41

You can reverse the direction of the data by specifying the data range with keywords. For example, to draw the plot with the Y axis reversed, type this:

IDL> plot, time, curve, YRange= [30 01

Your output should look similar to the illustration in Figure 5, below.

Figura 4: Un símbolo de dibujo creado por UserSym producirá.

triple color que describen los colores carbón,amarillos y verdes.) Por ejemplo, cargue los colores carbón, amarillo y verde en índices de color 1,2 , y 3 así:

Para dibujar el simbolo de amarillo en una base de carbón, teclee:

Si nada aparece en su ventana cuando teclea la orden arriba, es probable porque está corriendoIDL en muestras de colores de 24-bit y tiene la descomposición de color . Se estudiará más sobrecolorear la descomposición más tarde, pero para ahora, estando seguro de la descomposición de color se va ha usar. Representamos el tipo de color apropiado:

Si usted quiere sólo la línea que sea un color diferente, debe delinear primero los datos con ella palabra NoData, entonces redibuja la línea con la orden de OPlot ( discuta debajo de ). Por ejemplo, para tener un lote amarillo en una base de carbón, con los datos en verde, teclee:

Limitando el rango de trazos de líneaNo todos los datos deben ser trazados en un gráfico de líneas. Usted puede limitar la cantidad de datosque trama con palabras clave XRange. Por ejemplo, para trazar sólo los datos que se encuentran entre 2 y 4en el eje X, tipear esto:

O, para trazar sólo la parte de los datos que tiene los valores de Y entre 10 y 20 y Xvalores comprendidos entre 2 y 4, escriba:

Usted puede invertir la dirección de los datos, especificando el rango de datos con palabras clave YRange.Por ejemplo, para dibujar la gráfica con el eje de Y invertida, escriba lo siguiente:

El resultado debe ser similar a la ilustración de la figura 5, a continuación.

Page 9: Coyote Traduction

Siitzple Graphical Displays

Figure 5: A plot with the zero poirzt of the Y axis located ort the top of the plot.

If your chosen axis range doesn't fall within IDL's sense of what an aesthetically pleasing axis range should be, IDL may ignore the asked-for range. For example, t ~ y this command:

IDL> Plot, time, curve, XRange=[2.45, 5.641

The X axis range goes from 2 to 6, which is not exactly what you asked IDL to do. To

make sure you always get the axis range you ask for, set the XStyle keyword to 1 , like

this: IDL> Plot, time, curve, XRange=[2.45, 5.641, XStyle=l

You will learn more about the [XYZIStyle keywords in the next section.

Changing the Style of Line Plots It is possible to change many chasacteristics of your plots, including the way they look. For example, you may not case for the box style of the line plots. If not, you can change the plot characteristics with the [XYZIStyle keywords. The values you can use with these keywords to change line plot styles is shown in Table 5. For example, to eliminate box axes and have just one X axis and one Y axis, type:

IDL> Plot, time, curve, XStyle=8, YStyle=8

Table 5: A table of the key~vord values for the [XYZIStyle keywords that set properties for the axis. Note that values cart be added to specih more than one axis property.

Figura 5: una trama con el punto cero del eje Y localizado en la parte superior del trama.

Si tu rango de eje elegido no está comprendida en el sentido de iDL que en estetica el rango deleje debe ser agradable, IDL puede ignorar el pedido-para el rango. Por ejemplo, trate coneste comando:

El rango del eje X va de 2 a 6, lo cual no es exactamente lo que usted pidió hacer en IDL. asegurarse de que siempre obtendrá el rango del eje que pides, establece la palabra clave

XStyle a 1, al igual que esto:

Usted aprenderá más sobre la palabras clave [XYZ]Style en la siguiente sección.

Cambiando el estilo de líneas gráficas

Es posible cambiar muchas caracteristicas de sus líneas gráficas, incluyendo la forma en que lomira. Por ejemplo, usted no puede cargar el cuadro de estilo de los trazos de línea. Si no, ustedpuede cambiar las características de la trama con la palabras clave [XYZ] Style. Los valores quepuede utilizar con estas palabras clave para cambiar estilos de trazado de líneas se muestran enla Tabla 5. Por ejemplo, para eliminar los ejes de la caja y tener un solo eje X y un eje Y, escriba:

valor descripción de las propiedades del eje afectado

forzar exactamente el rango del eje

expandir el rango del eje

suprimir el eje entero

suprimir el estilo de caja del eje (dibibuja solo un eje)

inibe la posición de salida del eje Y con valor a 0. (solo el eje Y)

Tabla 5: Una table de valore de palabras claves para la palabra clave [XYZ]Style que ponen propiedades para el eje. Note que los valores pueden ser añadidos para especificar más deuna propiedad del eje.

Page 10: Coyote Traduction

Czrstoinizing Graphics Plots

You can turn an axis off completely. For example, to show the plot with a single Y axis, you can type:

IDL> Plot, time, curve, XStyle=4, YStyle=8

Your output should look similar to the illustration in Figure 6.

Figlcre 6: A plot with the X axis srcppressed aitd Y box axes turned off.

You could show the same plot with Y

axes

and Y grid lines:

IDL> Plot, time, curve, XStyle=4, YTickLen=l, YGridStyle=l

The [XYZIStyle keyword can be used to set more than one axis property at a time. This is done by adding the appropriate values together. For example, you see from Table 5 that the value to force the exact axis range is 1, and the value to suppress the drawing

of box axes is 8. To both make an exact X axis range and to suppress box axes, these values are added together, like this:

IDL> Plot, time, curve, XStyle=8+1, XRange= [ 2 , 5 ]

To create a full grid on a line plot is accomplished (strangely) with the TickLerz keyword, like this:

IDL> Plot, time, curve, TickLen=l

Outward facing tick marks are created with a negative value to the [XYZlTickLe~z

keywords. For example, to create all outward facing tick marks, type:

IDL> Plot, time, curve, Tick~en=-0.03

To create outward facing tick marks on individual axes, use the [XYZITickLerz

keywords. For example,

to have outward

facing

tick marks on

just

the X

axis, type:

IDL> Plot, time, curve, XTickLen=- 0.03 You can also select the number of

major and minor tick marks on an axis with the [XYZITicks and [XYZIMinor keywords. For example to create the plot with only two major tick intervals, each with 10 minor tick marks, on the X axis, type: IDL> Plot, time, curve, XTicks=2, XMinor=lO, XStyle=l

Puede activar un eje completamente. Por ejemplo, para mostrar la trama con un solo eje Y,se puede escribir:

El resultado debe ser similar a la ilustración en la Figura 6.

Figura 6: Una grafíca con el eje de X suprimidó y la caja del eje Y apagada

Se podría mostrar la misma grafica con el eje Y y líneas de cuadrícula:

La palabra clave [XYZ]Style se puede utilizar para establecer más de una propiedad de eje a la vez.Este se realiza mediante la adición de los valores adecuados en conjunto. Por ejemplo, se ve en la Tabla 5 el valor para forzar el rango exacto del eje es 1, y el valor para suprimir el dibujo de los ejesde la caja es de 8. Para ambos hacen un rango exacto de eje X y para suprimir los ejes de la caja, estos valores se suman, de esta manera:

Para crear un grillado completo en un diagrama de puntos se realiza (extrañamente) con lapalabra clave TickLen, por ejemplo:

externamente las marcas se crean con un valor negativo con la palabras clave [XYZ] TickLen.Por ejemplo, para crear todas las marcas exteriores, escriba:

Para crear externamente las marcas de los ejes individuales, utilice la palabras clave [XYZ] TickLen. Por ejemplo, para tener externamente las marcas sólo del eje X, escriba:

También puede seleccionar el número de marcas de mayor y menor grado de un eje con las palabras clave [XYZ]Tick y [XYZ]Minor. Por ejemplo, para crear la trama con sólo dos intervalos de graduaciónprincipal, cada uno con 10 marcas de graduación secundarias, en el eje X, escriba:

Page 11: Coyote Traduction

Sintple Graplzicnl Displays

Plotting Multiple Data Sets on Line Plots You are not restricted to just a single data set on a line plot. IDL allows you to plot as many data sets as you like on the same set of axes. The OPlot command is used for this purpose. Type the following commands. Your output will look like the illustration in Figure 7.

IDL> Plot, curve IDL> OPlot, curve/2.0, LineStyle=l IDL> OPlot , curve/5.0, LineStyle=2

Figure 7: An unlimited number of data sets can be plotted on the same line plot.

Figure 8: A line plot with two Y axes. The second axis is positioned with the Axis command. Be sure to save the data scaling with the Save keyword.

The initial Plot command establishes the data scaling (in the !X.S and !XS scaling parameters) for all the subsequent plots. In other words, it is the values in the !X.S and !Y;S system variable that tells IDL how to take a point in data space and place it on the display in device coordinate space. Make sure the initial plot has axis ranges sufficient to encompass all subsequent plots, or the data will be clipped. Use the XRnrzge and YRarzge keywords in the first Plot command to create a data range large enough. To distinguish different data sets, you can use different line styles, different colors, differ-

Trazando múltiples conjuntos de datos en líneas gráficasUsted no está limitado a un solo conjunto de datos en un gráfico de líneas. IDL le permite dibujar muchos conjuntos de datos que quepa en el mismo conjunto de ejes. El comando Oplot se utilizapara este propósito. Escriba los siguientes comandos. Su salida será similar a la ilustraciónen la Figura 7.

Figura 7: Un número ilimitado de conjuntos de datos se puede mostrar en el mismo grafico de línea.

Figura 8: un grafíca de línea con dos ejes Y. El segundo eje se sitúa en una posición convenientecon el comando Axis. Esté seguro de salvar los datos usando la palabra clave Save.

El comando inicial Plot establece la escala de datos (en el ! X.S y ! Y.S Escalado parámetros) paratodas las tramas subsiguientes. En otros palabras, se trata de los valores en el sistema de Variable! X.S y ! Y.S que dice IDL cómo sacar un punto en el espacio de datos y colóquelo para mostrar enel espacio de coordenadas del dispositivo. Asegúrese de que la parcela inicial tenga rangos de ejessuficientes para abarcar todas las parcelas posteriores o se recortarán los datos. Utilice las palabrasclaves XRange y YRange en el primer comando Plot para crear una serie de datos suficientemente grande. Para distinguir los diferentes conjuntos de datos, puede utilizar diferentes estilos de línea, diferentes colores, diferentes símbolos , etc

Page 12: Coyote Traduction

Creatirtg Sztrface Plots

ent plot symbols, etc. The OPlot command accepts many

of the same keywords the

Plot command accepts.

IDL> TvLCT, [255, 255, 01, [O, 255,

2551, [O, 0, 01, 1

IDL> Plot, curve, / ~ o ~ a t a IDL> OPlot, curve, Color=l

IDL> OPlot, curve/2.0, Color=2 IDL> OPlot , curve/5.0, Color=3

Plotting Data on Multiple Axes Sometimes you wish to have two or more data sets on the same line plot, but you want the data sets to use different Y axes. It is easy to establish as many axes as you need with the Axis command. The key to using the Axis command is to use the Save keyword to save the proper plot scaling parameters (i.e., those stored in the !X.S and !Y;S system variables) for subsequent plotting calls.

For example, here one plot is drawn and the Axis command along with the Save keyword is used to establish a second Y axis. The curve in the OPlot command will use the scaling factors saved by the Axis command to determine its placement on the plot. The proper commands are these:

IDL> Plot, curve, YStyle=8, YTitle= 'Solid Line' , $ Position = [0.15, 0.15, 0.85, 0.951

IDL> Axis, YAxis=l, YRange= [O, 2001 , /save, $ YTitle='Dashed Line'

IDL> OPlot , curve*5, LineStyle=2

The Positiorl keyword is used to position the first plot on the page. To learn more about the Positioi~ keyword, see "Positioning Graphic Output in the Display Window" on page 44. Your output will look like the illustration in Figure 8.

Creating Surface Plots Any two-dimensional data set can be displayed as a surface (with automatic hidden- line removal) in IDL with a single Surface command. First, you must open a data file. Use the LoadData command to open the Elevation Data data set, like this:

IDL> peak = LoadData (2)

You can see that this is a 41-by-41 floating point array by typing the Help command, like this:

IDL> Help, peak

This data can be viewed as a surface with a single command:

IDL> Surf ace, peak, CharSize=l. 5

Your output should look similar to the illustration in Figure 9.

Notice that if the Sutj4ace command is given just a single array as an argument it plots the array as a function of the number of elements (41 in the X and Y directions, in this case) in the array. (You used the CltarSize keyword to increase the character size so you can see this easily.) But, as you did before with the Plot command, you can specify values for the X and Y axes that may have some physical meaning for you. For example, the X and Y values may be longitude and latitude coordinates. Here we make a latitude vector that extends from 24 to 48 degrees of latitude and a longitude vector that extends from -122 to -72 degrees of longitude:

IDL> lat = FIndGen(41) * (24.0/40) + 24 IDL> lon = FindGen(41) * (50.0/40) - 122

El comando Oplot acepta muchas de las mismas palabras clave que el Comando Plot acepta.

Representación gráfica de datos sobre varios ejesA veces, usted desea tener dos o más conjuntos de datos en la misma línea argumental, pero deseaque los conjuntos de datos a utilizar esten en diferentes ejes Y. Es fácil establecer tantos ejes comosea necesario con el comando Axis. La clave para usar el comando Axis es utilizar la palabra clave Save para salvar los parámetros adecuados de escala (es decir, los que están almacenados en la Variables del sistema ! X.S y ! Y.S ) para las subsiguientes llamadas de trazado .Por ejemplo, he aquí una de las parcelas se dibuja y el comando Axis junto con la palabra clave savese utiliza para establecer un segundo eje Y. La curva en el comando Oplot se utilizar los factores deescala guardados por el comando de eje para determinar su colocación en la parcela. Los comandos apropiados son los siguientes:

La palabra clave Position se utiliza para colocar la primera parcela en la página. Para saber mássobre la palabra clave Posición , vea "La Salida gráfica de la ventana de visualización" en la página 44. Su salida será similar a la ilustración de la Figura 8.

Creación de gráficos de superficieCualquier conjunto de datos en dos dimensiones se puede mostrar como una superficie (con eliminación automática de lineas ocultas) en IDL con un simple comando Surface. En primer lugar, debe abrir un archivo de datos. Utilice el comando LoadData para abrir la el conjunto de datos deelevación, así:

Se puede ver que se trata de una matriz de punto flotante de 41-por-41 mediante el comando Help, así:

Estos datos pueden ser vistos como una superficie con un único comando:

El resultado debe ser similar a la ilustración de la Figura 9.

Tenga en cuenta que si el comando Surface da una sola matriz como un argumento, esta matriz es una función del número de elementos de la matriz (en este caso 41 en las direcciones X e Y). (Usaste la palabra clave CharSize para aumentar el tamaño de la fuente para que se puede ver estofácilmente.) Pero, como lo hizo antes con el comando Plot, puede especificar los valores de los ejes X e Y, que pueden tener algún significado físico para usted. Por ejemplo, los valores X e Y pueden ser coordenadas de longitud y latitud. Aquí hacemos un vector de latitud que se extiende de 24 a 48 grados de latitud y una longitud este vector que se extiende desde -122 hasta -72 grados de longitud:

Page 13: Coyote Traduction

Sinzple Graphical Displays

Figure 9: A basic surface plot of elevatiolz data.

IDL> Surface, peak, lon, lat, XTitle='Longitudel, $ YTitle='Latitudel, ZTitle='Elevationl, Charsize=1.5

Your output will look like the illustration in Figure 10.

Figure 10: A surface plot with meatzirtgful values associated with its axes.

The parameters Ion and lat in the command above are monotonically increasing and regular. They describe the locations that connect the surface grid lines. But the grid does not have to be regular. Consider what happens if you make the longitudinal data points irregularly spaced. For example, you can simulate randomly spaced longitudinal points by typing this:

IDL> seed = -lL IDL> newlon = RandomU(seed, 41) * 41 IDL> newlon = newlon[Sort (newlon) ] * (24 ./40) + 24 IDL> Surface, peak, newlon, lat, ~Title='Longitude~, $

YTitle='Latitudel, ~ ~ i t l e = ~ E l e v a t i o n ~ , Charsize=1.5

You see now that the longitudinal X values are not regularly spaced. Although it may look like the data is being re-sampled, it is not. You are simply drawing the surface

Figura 9: Una gráfica de superficie basica de elevacion de datos.

Su salida será similar a la ilustración de la figura 10.

Figura 10: Una gráfica de superficie con los valores significativos asociados con sus ejes.

Los parámetros Lon y Lat en el comando anterior se imcrementaron monótonamente y regularmente. Describiendo los lugares que se conectan las líneas de la cuadrícula de superficie. Pero la cuadrícula no tiene que ser regular. Considere lo que sucede si usted hace los datos longitudinales sean puntos espaciados irregularmente. Por ejemplo, puedesimular espaciados al azar con puntos longitudinales escribiendo esto:

Tu veras, ahora que los valores longitudinales X no están espaciados regularmente. Aunque puedeparece que los datos están siendo re-muestreados, no lo es. Simplemente estás dibujando la superficielíneas de la cuadrícula en las ubicaciones especificadas por puntos de datos de longitud y latitud.

Page 14: Coyote Traduction

Cztstorniziitg Sztrface Plots

grid lines at the locations specified by the longitude and latitude data points. Your output should be similar to the illustration in Figure l l .

Figzcre 11: The same surface plot, bzrt with alz irregularly spaced X vector.

Customizing Surface Plots There are over 7 0 different keywords that can modify the appearance of a surface plot. In fact, many of these keywords you already learned for the Plot command. For example, you saw in the code above that the same title keywords can be used to annotate the axes. Notice, however, that when you add a Title keyword that the title is rotated so that it is always in the XZ plane of the surface plot. For example, type this:

IDL> Surface, peak, lon, lat, ~ ~ i t l e = ~ L o n g i t u d e ~ , $

~~itle=~Latitude', Title='Mt. Elbertl, Charsize=1.5

This is not always what you want. If you want the plot title to be in a plane parallel to the display, you will have to draw the surface with the Surfnce command, and the title with the XYOutS command. (There is detailed information on the XYOutS command on page 5 1 .) For example, like this: IDL> Surface, peak, lon, lat, X~itle='Longitude', $

YTitle='Latitude', Charsize=1.5

IDL> XYOutS, 0.5, 0.90, /Normal, Size=2.0, Align=0.5, $ 'Mt. Elbertl

Rotating Surface Plots

You may want to rotate the angle at which you view a surface plot. A surface plot can be rotated about the X axis with the Ax keyword and about the Z axis with the Az keyword. Rotations are expressed in degrees counterclockwise as you look from positive values on the axis towards the origin. The Az and h keywords default to 30 degrees if they are omitted. For example, to rotate the surface about the Z axis by 60 degrees and about the X axis by 35 degrees, type:

IDL> Surf ace, peak, lon, lat, Az=60, Ax=35, Charsize=l. 5

Your output should look like the illustration in Figure 12.

Although direct graphics surface commands are still useful in IDL, many programmers are finding that surfaces rendered with

the object graphics class library

Su salida debería ser similar a la ilustración de la figura 11.

Figura 11: El mismo grafico de superficie, pero con un vector X irregularmente espaciado.

Personalizando los graficos de SuperficieHay más de 70 diferentes palabras clave que pueden modificar la apariencia de un gráfico desuperficie. De hecho, muchas de estas palabras clave se ha aprendido para el comando Plot. Por ejemplo, se vio en el código anterior que el mismo título palabras clave puede utilizarse paraanotar los ejes. Nótese, sin embargo, que cuando se agrega la palabra clave Title al título estegira de manera que siempre está en el plano XZ del gráfico de superficie. Por ejemplo, escribalo siguiente:

Esto no siempre es lo que quieremos. Si deseamos que el título del grafico este en un plano paraleloa la pantalla, tendrá que dibujar la superficie con el comando Surface, y el título con el comando XYOutS. (Hay información detallada sobre el comando XYOutS en la página 51) Por ejemplo, comoesto.:

Rotando la grafica de SuperficieEs posible que desee rotar un gráfico de superficie un ángulo para verlo. Un gráfico de superficiepuede girarse alrededor del eje X con la palabra clave Ax y alrededor del eje Z con la palabra clave Az. Las rotaciones se expresan en grados hacia la izquierda cuando se mira desdelos valores positivos sobre el eje hacia el origen. Las palabras claves Az y Ax por defecto a 30grados si se omiten. Por ejemplo, para hacer girar la superficie alrededor del eje Z por 60grados y sobre el eje X de 35 grados, escriba:

El resultado debe ser similar a la ilustración de la figura 12.Aunque los comandos de superficie gráfica directos siguen siendo útiles en IDL, muchosprogramadores están encontrando que las superficies representan al objeto en clases de bibliotecas gráficas.

Page 15: Coyote Traduction

Siittple Graplzical Displays

Figure 12: Surface plots can be rotated with tlze Ax arzd Az key~vords.

are much more useful to them, especially when surface rotations are desired. Partly this is because direct graphics surface rotations have an artificial limitation that requires the Z axis to be pointing in a vertical direction in the display window. No such limitation exits for object graphics surfaces.

To see what some of the advantages are, run the program FSC-Sutface, which is among the program files you downloaded to use with this book. Press and drag the cursor in the graphics window to rotate the surface plot. Controls in the menu bar give you the opportunity to set many properties of the surface plot, including shading parameters, lights, and colors. The FSC-Sulface program looks similar to the illustration in Figure 13.

Adding Color to a Surface Plot Sometimes you want to add color to the surface plot to emphasize certain features. It is easy to add color, using many of the same keywords that you used to add color to line plots. (Colors are discussed in detail in "Working with Colors in IDL" on page 8 1. For now, just type the TvLCT command below. You will learn exactly what the command means later. Basically, you are loading three color vectors that describe the red, green, and blue components of the color triples that describe the charcoal, yellow, and green colors.) For example, to create a yellow surface plot on a charcoal background, type:

IDL> TvLCT, [70, 255, 01, 170, 255, 2551, [70, 0, 01, 1 IDL> Device, Decomposed=O IDL> Surf ace, peak, Color=2, Background=l

If you wanted the underpart of the surface to be a different color than the top, say green, you can use the Bottoln keyword like this:

IDL> Surface, peak, Color=2, Background=l, Bottom=3

If you wanted the axes to be drawn in a different color-green, for example-than the surface, you have to enter two commands. The first command uses the NoData keyword so that just the axes are drawn, while the second command draws the surface itself with the axes turned off. See Table 5 on page 26 for a list of values you can use with the [XYZIStyle keywords and what they mean.

IDL> Surface, peak, Color=3, /NoData IDL> Surface, peak, / ~ o ~ r a s e , Color=2, Bottom=l, $

XStyle=4, YStyle=4, ZStyle=4

Figura 12: Las graficass superficiales se pueden rotar con las palabras claves Ax y Az.

son mucho más útiles para ellos, especialmente cuando se desean rotaciones de superficie. En parteesto se debe a gráficos de superficie rotadas directamente que tienen una limitación artificial querequiere el eje Z a estar apuntando en una dirección vertical en la ventana de visualización. Tales salidas no limitación de superficies de objetos gráficos. Para ver cuáles son algunas de las ventajas,ejecute el programa de FSC_Surface, que esta entre los archivos de programa que ha descargado parasu uso con este libro. Pulse y arrastre el cursor en la ventana de gráficos para hacer girar el gráfico de superficie. Los controles en la barra de menús le ofrece la oportunidad de establecer muchas propiedades de la superficie grafica, incluyendo el sombreado de parámetros, luces y colores. El programa de FSC_Surface tiene una apariencia similar a la ilustración en la Figura 13.

Adiciónando color a una superficie gráfica

A veces quieres añadir color a la superficie gráfica para enfatizar ciertas características. Esfácil de agregar color, usando muchas de las mismas palabras clave que utilizó para dar colora gráficas de líneas. (Los colores se discuten en detalle en la página 81 (Trabajar con colores en IDL). Por Ahora, sólo tienes que escribir el comando TvLCT. Usted aprenderá exactamente lo que el comando significa más tarde. Básicamente, usted está cargando tres vectores de color que describen los componentes rojo, verde y azul de los colores triples que describen al carbón,amarillo y verde) Por ejemplo, para crear un gráfico de superficie de color amarillo sobre un fondo de carbón, tipee lo siguiente.:

Si usted quisiera la región inferior de la superficie un color diferente al de la parte superior,se puede utilizar la palabra clave Bottom así:

Si querías que los ejes se puedan dibujarse de un color verdoso diferente, por ejemplo lasuperficie, se tiene que introducir dos comandos. El primer comando utiliza la palabra clave NoDatapara que sólo los ejes se dibujan, mientras que el segundo comando representa la superficie en sí con los ejes apagados. Ver Tabla 5 en la página 26 para una lista de valores que puede utilizarcon la palabras clave [XYZ]Style y lo que significan.

Page 16: Coyote Traduction

Custontiziltg Srirface Plots

Figz~re 13: Tlze FSC-Surface program. Click aizd drag in the grapltics ~viitdow to rotate tlzis surface plot. Tlze program is written usiizg the object graplzics class library. Properties of tlze surface caiz be chaizged via optioizs iiz the meizzc bar.

It is also possible to draw the mesh lines of the surface in different colors representing a different data parameter. For example, you can think of draping a second data

set over the first, coloring the mesh of the first data set with the information contained in the second.

To see how this would work, open a data set named Snow Pack and display it as a surface with these commands. Notice that the Srzow Pack data set is the

same size as the peak data set, a 41-by-41 floating point array.

IDL> snow = LoadData (3) IDL> Help, snow IDL> Surface, snow

Now, you will drape the data in the variable srzow over the top of the data in the

variable peak, using the values of srlow to color the mesh of peak. First, load some

colors in the color table with the LoadCT command. The actual shading is done with

the Slzades keyword, like this:

IDL> LoadCT, 5 IDL> Surface, peak, Shades=BytScl(snow,

Top=!D.Table-Size-l)

Notice you had to scale the snow data set (with the BytScl command) into

either the

number of colors you are using in this IDL session or the size of the color

table. If you

failed to scale the data, you might see a set of axes and no surface display at all.

This is

because the data must be scaled into the range 0 to 255 to be used as the

shading

parameters for the surface.

Figure13: Programa de Tlze FSC_Surface. Haga clic y arastre sobre la ventana de gráficos para rotar la superficie grafica. El programa es escrito usando la biblioteca de clase de gráficos de objeto. Propiedades de la superficie se pueden cambiar por la via options en la barra de menú.

También es posible dibujar las líneas de malla de la superficie en diferentes colores que representanun parámetro de datos diferente. Por ejemplo, usted puede pensar en cubrir con una segunda serie de datos sobre la primera, la coloración de la malla del primer conjunto de datos con la información contenida enel segundo.Para ver cómo funcionaría esto, abra un conjunto de datos llamado Snow Pack y mostrarlo como unsuperficie con estos comandos. Observe que el conjunto de datos Snow Pack es del mismo tamañoque el conjunto de datos máximo, una matriz de puntos flotante 41 por 41 .

Ahora, se le colocan los datos en la variable snow a lo largo de la parte superior de los datos en lavariable peak, utilizando los valores de snow para dar color a la malla de peak. En primer lugar, cargaralgunos colores en la tabla de colores con el comando LoadCT. El sombreado real se realiza conla palabra clave Shades, así:

Observe que tenía que escalar el conjunto de datos Snow (con el comando BytScl) en cualquiera de los número de colores que está usando en esta sesión IDL o el tamaño de la tabla de colores. Sino logró escalar los datos, es posible que vea un conjunto de ejes y no presenten la superficie en absoluto. Es porque los datos deben ser escalados en el rango de 0 a 255 para ser utilizado como el sombreado de parámetros para la superficie.

Page 17: Coyote Traduction

Si~ttple Graphical Displays

Sometimes you might like to display the surface colored according to elevation. This is easily done just by using the data itself as the shading paranleter.

IDL> Surface, peak, Shades=BytScl(peak, Top=!D.Table-Size-l)

Modifying the Appearance of a Surface Plot There are a number of keywords you can use to modify the appearance or style of a surface plot. For example, you can display the surface with a skirt. Use the Skirt keyword to indicate the value where the skirt should be drawn. For example, try these commands:

IDL> Surface, peak, Skirt=O IDL> Surface, peak, Skirt=5OO, Az=60

The output of the first command above should look similar to the illustration in Figure 14.

Figure 14: The surface plot with a skirt oiz the surface.

You can obtain a kind of "stacked line plot" appearance by drawing only horizontal lines. For example, type:

IDL> Surf ace, peak, /~orizontal

If you like, you can display just the lower or just the upper surface and not both (which is the default) using keywords. For example, type the following two commands:

IDL> Surface, peak, /upper-only IDL> Surface, peak, /~ower-Only

Sometimes you might want to draw just the surface itself with no axes:

IDL> Surface, peak, XStyle=4, YStyle=4, ZStyle=4

Creating Shaded Surface Plots It is equally easy to create shaded surface plots of your data. To create a shaded surface plot using a Gouraud light source shading algorithm, type:

IDL> Shade-Surf, peak

The Slznde-Sutfcommand accepts most of the keywords accepted by the Surjnce command. So, for example, if you want to rotate the shaded surface, you can type this:

sólo mediante el uso de los datos en sí como el parametro sombreado.A veces te gustaría mostrar la superficie de color de acuerdo a la elevación. Esto es fácil de hacer

Modificando la apariencia de un gráfico de superficieHay una serie de palabras clave que puede utilizar para modificar la apariencia o el estilo de ungráfico de superficie. Por ejemplo, puede mostrar la superficie con un bordeado. Utilice la palabra clave Skirt para indicar el valor que debe establecerse el bordeado. Por ejemplo, pruebeestos comandos:

La salida del primer comando de arriba debe ser similar a la ilustración de la Figura 14.

Figura 14: La gráfica superficial con una bordeado en la superficie.

Usted puede obtener una especie de "bordeado de grafica de lineas" apariencia de dibujo de sólo líneas horizontales. Por ejemplo, escriba:

Si lo desea, puede mostrar sólo la superficie inferior o igual al superior y no tanto (que es el valorpredeterminado) utilizando las palabras claves. Por ejemplo, escriba los dos comandos siguientes:

A veces es posible que desee extraer sólo la propia superficie sin ejes:

Creando Superficie gráficas sombreadasEs igualmente fácil para crear gráficas de superficies sombreadas con sus datos. Para crearun sombreado de la superficie utilizando un algoritmo de sombreado Gouraud fuente de luz , escriba:

El comando Shade_Surf acepta la mayoría de las palabras clave aceptadas por el comando Surface. Así, por ejemplo, si desea girar la superficie sombreada, puede escribir esto:

Page 18: Coyote Traduction

Creatiitg Shaded Szirface Plots

IDL> Shade - Sur f , peak, lon, l a t ,

Az=45,

A x = 3 0

Your output should look similar to the illustration in Figure

15.

Figure 15: A shaded surface plot of the elevatioiz data usiizg a Gourazcd light sozcrce shading algoritlzm.

Changing the Shading Parameters The shading parameters used by the Slzade-Sutfcommand can be changed

with the

Set-Shading command. For example, to change the light source from the

default of [0,0,1], in which the light rays are parallel to the Z axis, to [1,0,0], in which the light rays are parallel to the X axis, type:

IDL> Set-Shading, Light= [ l , 0 , 01 IDL> Shade-Surf , peak

You can also indicate which color table indices should be used from the color table for shading purposes. For example, suppose you wanted to load the Red Temperature color table (color table 3) into color indices 100 to 199 and use these for the shading colors. You could

type this: IDL> LoadCT, 3 , NColors=100, Bottom=100

IDL> Set Shading, Values= [100, 1991

IDL> shade - Sur f , peak

Be sure to set the light source location and color value parameters back to their original values, or you will be confused as you move on with the exercises. IDL> LoadCT, 5

IDL> set-Shading, Light= [0, 0, l] , Values= [ o , ! D . able-size-l]

Using Another Data Set For the Shading Values Like with the Su~face command, another data set can provide the shading values with which to color the first. As before, you use the Shades keyword to specify the color index of each point on the surface. The shading of each pixel is interpolated from the surrounding data set values. For example, here is what the silow variable looks like as a shaded surface. Type:

IDL> Shade-Surf, snow

Now use this data set to shade the original elevation data. Type:

El resultado debe ser similar a la ilustración de la figura 15.

Figura 15: Una gráfica de superficie sombrada de datos de elevación uzando una fuente de luz algoritmo de sombra Gouraud.

Cambiando los parámetros de sombreadoLos parámetros de sombreado utilizados por el comando Shade-Surf se pueden cambiar con elComando Set-Shading. Por ejemplo, para cambiar la fuente de luz por defecto de [0,0,1], en la que los rayos de luz que son paralelos al eje Z, a [1,0,0], en el que la luz son rayos paralelos al eje X, tipo:

También puede indicar que los índices de la tabla de colores se deben utilizar en el cuadro de color paraefectos de sombreado. Por ejemplo, suponga que desea cargar la Red de Temperatura la tabla de colores (tabla de colores 3) en índices de color del 100 al 199 y el uso de estos para el colorde sombreado. Usted puede escribir lo siguiente:

Asegúrese de establecer la ubicación de la fuente de luz y de los parámetros de valor de color de nuevoa sus valores originales, o se confundira en cuanto segamos mas adelante con los ejercicios.

Usando otros conjuntos de datos para los valores de sombreadoAl igual que con el comando Surface, otro conjunto de datos puede proporcionar los valores de sombreado para colorear el primero. Al igual que antes, se utiliza la palabra clave Shades para especificar el índice de color de cada punto de la superficie. El sombreado de cada píxelse interpola a partir de la los datos que lo rodean. Por ejemplo, esto es lo que la variable Snow miré como una superficie sombreada. Tipear lo siguiente:

Ahora usa este conjunto de datos para dar sombra a los datos de elevación originales. Tipo:

Page 19: Coyote Traduction

Silnple Graphical Displays

IDL> Shade-Surf, peak, Shades=BytScl(snow,Top=!D.Table-Size)

Your output should look like the illustration in Figure 16.

Figure 16: The peak elevation data shaded with tl2e sizow data set.

If you want to shade the surface according to its elevation values, simply byte scale the data set itself, type this:

IDL> Shade - Surf, peak, Shades=BytScl(peak, Top=!D.Table-Size)

Draping another data set over a surface is a way to add an extra dimension to your data. For example, by draping a data set on a three-dimensional surface, you are visually representing four-dimensional information. If you were to animate these two data sets over time you would be visually representing five-dimensional information. (To learn about data animation see "Animating Data in IDL" on page 102.)

Sometimes you just want to drape the original surface on top of the shaded surface. This is easy to do simply by combining the Shade-Suifand Su$ace commands. For example, type:

IDL> Shade Surf, peak IDL> surf ace, peak, / ~ o ~ r a s e

Creating Contour Plots Any two-dimensional data set can be displayed in IDL as a contour plot with a single Corztot~r command. You can use the peak variable if you already have it defined in this IDL session. If not, use the LoadData command to load the Elevatior? Data data set, type this:

IDL> peak = LoadData (2 ) IDL> Help, peak

This data can be viewed as a contour plot with a single command:

IDL> Contour, peak, CharSize=1.5

Notice that if the Coiztour command is given just the single 2D array as an argument it plots the data set as a function of the number of elements (41 in each direction) in the 2D array. But, as you did before with the Surface command, you can specify values for the X and Y axes that may have physical meaning for you. For example, you can use the longitudinal and latitudinal vectors from before, like this:

El resultado debe ser similar a la ilustración de la Figura 16

Figura 16: Los datos máximos de elevación se oscurecer con el conjunto de datos snow.

Si desea sombrear la superficie de acuerdo a sus valores de elevación, simplemente la escala bytedel conjunto de datos en sí, escriba lo siguiente:

Cubriendo otro conjunto de datos sobre una superficie es una manera de añadir una dimensión extra a su datos. Por ejemplo, cubriendo un conjunto de datos en una superficie en tres dimensiones, que representan visualmente la información de cuatro dimensiones. Si se va a animar a estos dos conjuntos

de datos a través del tiempo que estaría representando visualmente la información de cinco dimensiones.(Para obtener información acerca de la animación de datos consulte "Animación de datos de IDL" en lapágina 102.)

A veces se desea cubrir la superficie original en la parte superior de la superficie sombreada.Esto es fácil de hacer, simplemente mediante la combinación de los comandos Shade_Surf y surface. Porejemplo, escriba:

Creando gráficos de contornoCualquier conjunto de datos en dos dimensiones se puede mostrar en IDL como un gráfico de contorno con un simple Comando Contour. Usted puede utilizar la variable peak si ya lo han

definido en este Sesión de IDL. Si no es así, utilice el comando LoadData para cargar el conjunto de elevación,escriba lo siguiente:

Estos datos pueden ser vistos como un gráfico de contorno con un solo comando:

Tenga en cuenta que si el comando Contour nos da sólo la única matriz 2D como el argumento degrafica del conjuntos de datos es una función del número de elementos (41 en cada dirección) en elmatriz 2D. Pero, como lo hizo antes con el comando de superficie, puede especificar los valorespara los ejes X e Y, que pueden tener significado físico para usted. Por ejemplo, puede utilizar los vectores longitudinales y latitudinales, de esta manera:

Page 20: Coyote Traduction

Creating Contolir Plots

Figure 17: A basic corttozcr plot of the data. Notice that tlze X artd Y axis labels rep- resent the ~zzcmber of elemertts irz tlze data array.

IDL> lat = FIndGen(41) * (24. / 40 ) + 24 IDL> lon = FindGen(41) * 50 .0 /40 - 122 IDL> Contour, peak, lon, lat, XTitle='Longitudel, $

YTitle='Latitudel

Notice that the axes are being autoscaled. You can tell this in a couple of ways. First, the contour lines do not go to the edges of the contour plot, and you can see that the labels on the axes are not the same as the minimum and maximum values of the lor~ and lnt vectors.

IDL> Print, Min(1on) , Max(1on) IDLz Print, Min (lat) , Max (lat)

To prevent autoscaling of the axes, set the XStyle and YStyle keywords, like this:

IDL> Contour, peak, lon, lat, XTitle='Longitudel, $ YTitle='Latitudel, XStyle=l, YStyle=l

You see the result of this command in the illustration in Figure 18.

-120 -l 10 -100 -90 -80 Longitude

Figure 18: A contozcrplot with axes representing physically meanirzgful quantities.

37

Figura 17: Una grafica de contorno básico de los datos. Notece que las etiquetas de los ejes X e Yrepresentan el número de elementos en la matriz de datos.

Notar que los ejes son autoescalados. Usted puede decidir como asociarlas. En primer lugar, el contorno de Iineas No puede ir en los bordes del contorno de gráficas, y usted puede ver que las etiquetas los ejes no son las mismas con los valores mínimo y máximo del vector lon y lat.

Para evitar autoescala de los ejes, use las palabras claves Xstyle y YStyle, como esto:

Usted verá el resultado de este comando en la Figura 18.

Figura 18: Una gráfica de contornos con ejes representando cantidades físicamente significativas.

Page 21: Coyote Traduction

Sinzple Gi.aplzical Displays

In earlier versions of IDL, the Corztour command used what was called the cell drnvvilzg r.tzetlzod of calculating and drawing the contours of the data. In this method the contour plot was drawn from the bottom of the contour plot to the top. This method was efficient, but it didn't allow options like contour labeling. The cell follo~ililzg lnetlzod was used to draw each contour line entirely around the contour plot. This took more time, but allowed more control over the contour line. For example, it could be interrupted to allow the placement of a contour label. The cell following method could be selected with the Follow keyword:

IDL> Contour, peak, lon, lat, XStyle=l, ~Style=l, /~ollow

Starting in IDL 5 the contour command always uses the cell following method to draw contours, so the Follow keyword is obsolete. But it is still used for its beneficial side- effect of labeling every other contour line automatically.

Selecting Contour Levels By default, IDL selects six regularly spaced contour intervals (five contour lines) to contour, but you can change this in several ways. For example, you can tell IDL how many contour levels to draw with the NLevels keyword. IDL will calculate that number of regularly spaced contour intervals. For example, to contour a data set with 12 regularly spaced contours, type:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, /~ollow, $ NLevels=12

Your output should look similar to the illustration in Figure 19. You can choose up to 29 contour levels.

Figure 19: A corztourplot with the izzlmber of contour levels set to 12. Note that ev- ery other contour level is labeled. This is a side-effect of zcsiizg the Follow keyword.

Unfortunately, although the IDL documentation claims that IDL will select a specified number of "equally spaced" contour intervals, this may not happen. If you look closely at the contour plot you just made, you will notice that fewer than 12 levels are calculated by IDL. Apparently, the NLevels keyword value is used as a "suggestion" by the contour-selecting algorithm in IDL.

Thus, most IDL programmers choose to calculate the contour levels themselves. For example, you can specify exactly where the contours should be drawn and pass them

En versiones anteriores de IDL, el comando Contour utiliza lo que se llama el "cell drawing method"y dibujo de los contornos de los datos de dibujo. En este método la curva de nivel que se extrae de laparte inferior del gráfico de contorno a la parte superior. Este método era eficiente, pero no permitia opciones como el etiquetado de contorno. La "cell following method" se usaba para dibujar cada línea de contorno completo alrededor del gráfico de contorno. Esto tomó más tiempo, pero permite un mayor control sobre la línea de contorno. Por ejemplo, se podría interrumpir para permitir la colocación de una etiqueta de contorno. La "cell following method" podría ser seleccionado con la palabra clave Follow:

A partir de IDL 5 el comando contour siempre se utiliza el "cell following method" para dibujar curvas de nivel, por lo que la palabra clave Follow es obsoleta. Sin embargo, todavía se utiliza por su efecto secundario beneficioso de etiquetar cada línea de contorno de forma automática.

Seleccionando Niveles de contornoDe forma predeterminada, IDL selecciona seis intervalos regularmente espaciados de contorno (cinco curvas de nivel) para contornos, pero puede cambiar esto de varias maneras. Por ejemplo, usted puede decir cómo IDL dibujé muchos niveles de contorno con la palabra clave NLevels. IDL calculará el número de intervalos de contorno regularmente espaciados. Por ejemplo, para el contorno de un conjunto de datos con los 12 contornos regularmente espaciados, escriba:

El resultado debe ser similar a la ilustración de la figura 19. Usted puede elegir un máximo de29 niveles de contorno

Figura 19: Una gráfica de contorno con el número de los niveles de contorno a 12. Nota que cada dos el nivel de contorno se rotula. Esto es un de efecto lateral de usar la palabra clave Follow.

Desafortunadamente, a pesar de la documentación IDL, afirma que IDL se seleccione un determinado número de intervalos de contorno "equidistantes", esto no puede suceder. Si usted busca cerca el gráfico de contorno que acaba de hacer, te darás cuenta de quees menos de 12 niveles que es calculado por IDL. Al parecer, el valor de palabra clave NLEVELS se utiliza como una "sugerencia" por el algoritmo de contorno a seleccionar en IDL.Por lo tanto, la mayoría de los programadores IDL eligen para calcular los niveles de contorno a sí mismos.

Page 22: Coyote Traduction

Modifying n Coi~torii. Plot

to the Contoui- command with the Levels keyword, rather than with the NLevels keyword, like this:

IDL> vals = [200, 300, 600, 750, 800, 900, 1200, 15001 IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, /Follow, $

Levels=vals

To choose 12 equally spaced contour intervals, you can write code something like this:

IDL> nlevels = 12 IDL> step = (Max (peak) - ~in(peak) ) / nlevels IDL> vals = Indgen(nleve1s) * step + Min(peak) IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, /Follow, $

Levels=vals

If you like, you can specify exactly which contour line should be labeled with the C-Labels keyword. This keyword is a vector with as many elements as there are contour lines. (If the number of elements does not match the number of contour lines, the elements do not get re-cycled like they sometimes do with other contour keywords.) If the value of the element is 1 (or more precisely, if it is positive), the contour label is drawn; if the value of the element is 0, the contour label is not drawn. If there is no value for a particular contour line, the line is not labeled. For example, to label the first, third, sixth and seventh contour line, type:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, /Follow, $ Levels=vals, C-Labels= [l, 0, l, 0,O , 1 , 1 , 0 1

To label all the contour lines, you could use the Replicate command to replicate the value 1 as many times as you need. For example, type this:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, /Follow, $ Levels=vals, C-Labels=Replicate(l, nlevels)

Modifying a Contour Plot A contour plot can be modified with the same keywords you used for the Plot and Suiface commands. But there are also a number of keywords that apply only to the Contour command. These most often modify the contour lines themselves.

For example, to annotate a contour plot with axis titles, you can type:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, /Follow, XTitle='Longitudel, YTitle='Latitudet , $ CharSize=1.5, Title='Study Area 13F8g1, NLevels=lO

But, you can also specify annotations on the contour lines themselves by using the C-Anizotatior~ keyword. For example, you could label each contour line with a string label by typing:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, /~ollow, $ XTitle=lLongitudel,~~itle='Latitude', $ CharSize=1.5, Title='Study Area 13F89', $ C-Ann~tation=[~Low~,'Middle','High'], $ Levels=[200, 500, 8001

Your output should look similar to the illustration in Figure 20.

Changing the Appearance of a Contour Plot There are any number of ways to modify the appearance of a contour plot. Here are a few of them. One chasacteristic you can change is the style of the contour lines. (See

Por ejemplo, puede especificar exactamente donde los contornos deben elaborarse y pasarlasal comando Contuor con la palabra clave NLevels, como esto:

Para elegir 12 intervalos de contorno igualmente espaciodos , usted puede escribir el código algo así:

Si usted puede especificar exactamente que contornos líneas deberían ser etiquetado con la palabra clave C_Labels . Esta palabra clave es un vector con muchos elementos como contorno de líneas. (Si el número de elementos no empareja al número de contorno líneas, los elementos no pueden ser removidos por ello se hace a veces con otro palabras clave contuor.) Si el valor del elemento es 1 (O más precisamente, si es positivo ), la etiqueta de contorno es dibujado; si el valor de la elemento es 0, el contorno de etiquetas no es dibujado. Si no hay valor en particular para el contorno de linea, la línea no es etiquetada. Por ejemplo, para etiquetar el primero, tercero,sexto y séptimo contorno linea, escribir:

Para etiquetar todo el contorno líneas, usted podría utilizar el comando Replicate para replicar el valor 1 muchas veces como usted necesite. Por ejemplo, escriba esto:

Modificando un Contorno GráficoUn contorno gráfico puede ser modificado con la misma palabras clave usted ha utilizado con los

comandos Plot y Surface .Pero ahi también un número de palabras claves que podria aplicar sólo al comando contour . Estos más a menudo modificar el contorno líneas a sí mismos.

Por ejemplo, para anotar un contorno grafico con eje títulados, usted puede escribir esto:

Pero, usted puede también especificar anotaciones en los contornos líneas asi mismos usando la clave palabra C_Annotation. Por ejemplo, usted podría etiquetar cada contorno línea con un etiqueta de cadena escribiendo:

Su salida debe ser similar a la ilustración en La Figura 20.

Cambio la Apariencia de un Contorno GráficaAhí cualquier número de formas a modificar la apariencia de un contornos gráficas. Aquí son unos pocos de ellos. Una característica es que usted puede cambiar este estilo de contorno líneas.

Page 23: Coyote Traduction

Silnple Graplzical Displays

Study Area 13F89 4 0 1 " ' ' ' ' ' ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ 1

30 a, m .S C.' 20 (6 -I

10

0 I . . . . . . . . . b . . . . . . . . . , . d.'?m,, , . . , . .: 0 10 20 30 40

Longitude

Figzcre 20: Corttoui. lines cart be labeled with text yozc provide yourself.

Table 3 for a list of possible line style values.) For example, to make the contour lines dashed, type:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, $ /~ollow, C_LineStyle=2

If you wanted every third line to be dashed, you could specify a vector of line style indices with the C-Linestyle keyword. If there are more contour lines than indices, the indices will be recycled or used over. Type:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, /~ollow, $ NLevels=9, C_LineStyle=[0,0,2]

Your output should look similar to the illustration in Figure 21.

Figure 21: Yozc can rnodifi many aspects of a contourplot. Here every third contour lirte is drawit in a dashed line style.

The thickness of the contour lines can also be changed. For example, to make all contour lines double thick, type:

IDL> Contour, peak, Ion, lat, XStyle=l, YStyle=l, $

Figura 20: Lineas de Contornos pueden ser rotulados con texto que usted proporciona.

(Ver la Tabla 3 para un lista de posibles valores de estilo línea .) Por ejemplo, hacer el contorno de líneas discontinua, tipear:

Si usted desea cada tercera línea discontinua, usted podría especificar un vector de índices de estilo línea con la palabra clave C_LineStyle . Si estos contornos de líneas son índices, el índices puede ser reciclado o utilizado. Tipear:

Su salida debería ser similar a la ilustración en La Figura 21.

Figura 21: Puede modificar muchos aspectos de un grafico de contorno. Aquí cada tercer curva de nivel es contraída en un estilo de línea de rayas.

El grosor de las líneas de contorno puede también ser cambiado. Por ejemplo, para hacer que todas las curvas de nivel doblen su espesor, tipear esto:

Page 24: Coyote Traduction

Modifying n Contozcr Plot

You could make every other line thick by specifying a vector of line thicknesses, like this:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, $ NLevels=12, C-~hick=[1,2], /Follow

You can modify the contour plot so that you can easily see the downhill direction. For example, type:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, $ /~ollow, NLevels=12, ownhi hill

Your output should be similar to the illustration in Figure 22.

Figure 22: The Do~vizhill keyword is set to show the do~v~thill direction of the con- tour plot.

Adding Color to a Contour Plot There are many ways to add color to a contour plot. (Colors are discussed in detail in "Working with Colors in IDL" on page 81. For now, just type the TvLCT command below. You will learn exactly what the command means later. Basically, you are loading three color vectors that describe the red, green, and blue components of the color triples that describe the charcoal, yellow, and green colors.) For example, if you want a yellow contour plot on a charcoal background, you can type:

IDL> TvLCT, [70, 2551, 170, 2551, [70, 01, 1 IDL> Device, Decomposed=O IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, $

NLevels=lO, Color=2, Background=l, /~ollow

You can also color the individual contour lines using the C-Colors keyword. For example, if you wanted the contour lines in the plot above to be drawn in green, you can type:

IDL> TvLCT, 0, 255, 0, 3 IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, /~ollow, $

NLevels=lO, Color=2, ~ackground=l, C_Colors=3

The C-Colors keyword can also be expressed as a vector of color table indices, which will be used in a cyclical fashion to draw the contour lines. For example, you can use

Usted podría hacer otra línea grueso especificando un vector de línea de espesores, así:

Usted puede modificar el contorno gráfico así que usted puede ver fácilmente la dirección.

Por ejemplo, tipear :

Su salida debería ser similar a la ilustración en Figura 22.

Figura 22: La palabra clave Downhill es un conjunto que muestra la dirección del contorno gráfico.

Agregando Color para un Contorno gráficoAhí muchas formas a añadir color a un contorno gráfico. (Colores son discutido en detalle en IDL "Trabajo con Colores en IDL " en página 81. Por ahora, sólo usaremos el siguiente comando TvLCT. Usted entendera exactamente qué es lo que hace el comando más adelante. Básicamente, usted esta cargando tres vectores de colores que describen al rojo, verde, y azul componentes del color triples que describen a los colores carbón, amarillo, y verde.) Por ejemplo, si quisieras un amarillo decontorno gráfico con un fondo carbón, usted tipee esto:

Usted puede también colorear individualmente el contorno líneas usando la palabra clave C_Colors.Por ejemplo, si usted deseado que el contorno de líneas en la grafica de arriba en verde, usted puede tippear:

La palabra clave C_Colors puede también ser expresado como un vector de tabla de índices de color,

el cual puede ser utilizado en una moda cíclica para dibujar el contorno líneas.

Page 25: Coyote Traduction

Siirrple Graphical Displays

the Tek-Color command to create and load drawing colors for the contour lines, like this:

IDL> Tek Color IDL> TVLCT, [70, 2551, [70, 2551, [70, 01, 1 IDL> Contour, peak, lon, lat, XStyle=l, YStyle-l, $

NLevels=lO, Color=2, Background=l, $ C-Colors=IndGen (10) +2, /~ollow

It is also easy to use the C-Colors keyword to make every third contour line blue, while the rest are gseen. For example, type:

IDL> Contour, peak, lon, lat, ~ ~ t y l e = l , YStyle=l, $ NLevels=12, Color=2, ~ackground=l, $ C Colors= [3, 3, 41 , /~ollow

Creating a Filled Contour Plot Sometimes you don't just want to see contour lines, but you would like to see a filled contour plot. To create a filled contour plot, just use the Fill keyword. Here you first

load 12 colors into the color table for the fill colors. The color indices will be specified with the C-Colors keyword. For example, type:

IDL> LoadCT, 0 IDL> LoadCT, 4, NColors=12, Bottom=l IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, ill, $

NLevels=12, /~ollow, C-Colors=Indgen(l2)+1

Although it is not obvious from the display, there are problems with doing filled contours in this manner. In fact, there is a "hole" in this contour plot that is filled with the background color. You can see it more easily if you reverse the background and plotting colors. (This is what is done in Postscript, as a matter of fact, and what causes many IDL programmers to pull their hair in frustration.)

Figure 23: The coiztourplot showing the "hole" at the lowest corztour level.

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, ill, $

Por ejemplo, usted puede utilizar el comando Tek_Color para crear y cargar dibujos de colores para el contorno líneas, así:

Figura 23: El gráfico de contorno mostrando el "agujero" al nivel de contorno más bajo.

Esto es también fácil a utilizar la palabra clave C_Colors pone cada tercera línea de contorno en azul,mientras que el resto son verde. Por ejemplo, tipee esto:

Creando un Llenado de Contorno GráficoA veces usted no quiere ver contorno líneas, pero usted le gustaria ver un contorno de gráfica lleno. Para crear un llenado de contorno grafico, sólo utilizar la palabra clave Fill. Aquí usted primero carga 12 colores en la color tabla para el llenado de colores. Los índices de colores se pueden especificar

con la palabra clave C_Colors. Por ejemplo, tipear esto:

Aunque no es obvio mostrar, allí un problema como hacer contornos rellenos en este manera. De hecho, hay un "Hole" en este contorno gráfico con el fondo color lleno. Usted podia ver fácilmente el fondo y el trazado de colores. (Esto es hecho en PostScript y qué hace que muchos programadores IDL tiren su cabello de frustración.)

Page 26: Coyote Traduction

Creating n Filled Coiztoztr Plot

The reason for the hole is that IDL fills the space between the first and second contour lines with the first fill coloc It would seem to make more sense to fill the space between the 0th (or background) and first contour with the first fill color. But to get IDL to do that you have to specify your own contour intervals and pass them to the Contour command with the Levels keyword. This is usually done with code like this:

IDL> step = (Max(peak) - Min(peak) ) / 12.0 IDL> clevels = IndGen (12) *step + Min (peak)

Now you get the contour fill colors correct:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, /Fill, $ Levels=clevels, /Follow, C-Colors=Indgen(l2)+1, $ Background=!P.Color, Color=!P.Background

In general, it is a good idea to always define your own contour levels when you are working with filled contour plots. Moreover, if you are displaying your filled contour

plots along with a color bar, creating your own contour levels is the only way to make sure that your contour levels and the color bar levels are identical.

Figure 24: The same contour plot, bzct with the levels calculated aizd specified di- rectly. The hole is no~v filled and the correct nzcinber of levels is apparertt iiz the plot.

Sometimes you will want to fill a contour plot that has missing data or contours that extend off the edge of the contour plot. These are called opelz colztours. IDL can sometimes have difficulty with open contours. The best way to fill contours of this type, is to use the Cell-Fill keyword rather than the Fill keyword. This causes the Contour command to use a cell filling algorithm, which is not as efficient as the algorithm used by the Fill keyword, but which gives better results under these circumstances.

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, $ Levels=clevels, C-Colors=1ndgen(l2)+1, /cell-Fill

La razón para que el hueco es que IDL llena la espacio entre la primero y segundo líneas de contorno con el primero llena color. Lo haría parecer más sentido a llenar el espacio entre el cero (O fondo) y el primer contorno con la primer llena de color. Para conseguir que IDL haga lo que usted teniene especificado hacer sus propios contornos de intervalos y pasarlos con el comando contour con la palabra clave Levels . Esto es en general hecho con código como esto:

Ahora usted conseguio el contorno lleno de colores correcto:

En en general, es una bueno idea siempre definir su propio contorno niveles cuando usted están trabajando con llenado de contorno gráficos. Por otra parte, si usted muestra su llenado de contorno gráficos con una barra de color, la creación de su propio niveles contorno es sólo la manera de cerciorarse de su contorno de niveles y que los niveles de la barra de color sean idénticas.

Figura 24: La misma gráfica de contorno, pero con los niveles calculados y especificados directamente. El agujero es llenado ahora y el número correcto de niveles es el aparente en el gráfico.

A veces usted quiere llenar a voluntad un contorno gráfico que le faltan datos o contornos paraampliar el borde de los contorno gráficos. Estos son llamado contornos abiertos. IDL a veces puede tener dificultad con contornos abiertos. La mejor manera de llenar contornos de este tipo, es a utilizarla palabra clave Cell_Fill en ves de la palabra clave Fill. Este causas que el comando contour utiliza un algoritmo de llenado de celdas, que no es eficiente como el algoritmo utilizado por la palabra clave Fill, pero que nos da mejor resultados bajo estas circunstancias.

Page 27: Coyote Traduction

Siirtple Grapltical Displays

The Cell-Fill keyword should also be used if you are

putting your filled contour plots

on map projections. Otherwise, the contour colors will

sometimes be incorrect.

The cell filling algorithm sometinles damages the

contour plot axes. You can repair

them by drawing the contour plot over again without

the data. Like this:

IDL> Contour, peak, lon, lat, XStyle=l,

YStyle=l, $

Levels=clevels, /No~ata,

/No~rase, /F'ollow

Sometimes you want to see the contour lines on top of

the color-filled contours. This

is easily accomplished in IDL with the Overplot

keyword to the Contoul- command.

For example, type:

IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, $ Levels=clevels, ill, C Colors=IndGen(l2)+1

IDL> Contour, peak, lon, lat, ~ ~ ~ ~ l e = l , YStyle=l, /~ollow, $ Levels=clevels, /Overplot

Your output should look similar to the illustration in Figure 25.

Figztre 25: A contour plot with the contozcr lines overplotted oiz top of the filled con- tours.

Don't confuse the Overplot keyword with the NoErase keyword. They are similar, but definitely not the same. In a contour plot, the Overplot keyword draws the contour lines only, rzot the contour axes. The NoEmse keyword draws the entire contour plot without first erasing what is already on the display.

Positioning Graphic Output in the Display Window IDL has several ways to position line plots, surface plots, contour plots and other graphical plots (map projections, for example) in the display window. To understand how IDL positions graphics, however, it is important to understand a few definitions. The graphic positiorl is that location in the display window that is enclosed by the axes of the plot. The graphic position does not include axes labels, titles, or other annotation (see Figure 26 below). The graplzic region is that portion of the display window that includes the graphic position, but it also includes space around the graphic position for such things as axes labels, plot and axes titles, etc. The graphic margin is defined as the area in the display window that is rzot the graphic position.

The graphic position may be set by !l?Positiolz system variable or by the Positiol? keyword to the Plot, Surface, Corztour, or any of the other IDL graphics commands.

La palabra clave Cell_Fill debería también ser utilizado si usted quiere llenar su contorno gráfica en el mapa de proyecciones. De lo contrario, los colores de contorno pueden ser a veces incorrectos.La algoritmo de llenado de celdas a veces daños al eje de contornográficos. Usted puede repararlos dibujando el contorno de graficos encima de nuevo sin la datos. Como esto:

A veces usted quiere ver el contorno líneas superior de contornos llenos de color. Es fácilmente de

logrado en IDL con la palabra clave Overplot para el comando Contour. Por ejemplo:

Su salida debería ser similar a la ilustración en Figura 25.

Figura 25: Una gráfica de contorno con el contorno de lineas overplot encima de los contornos llenos.

No confundir la palabra clave Overplot con la palabra clave NoErase . Ellos son similares, pero sin duda no la misma. En un contorno gráfico, la palabra clave Overplot señala sólo a la líneas de contorno, no los ejes de contorno. La palabra clave NoErase dibuja todo el contorno gráfico sin borrar primero la qué ya esta mostrada.

Posicionamiento de Salida Gráfico en la Ventana Mostrada IDL tiene varios formas a posición línea gráficas, superficie gráficas, contorno gráficas y otrasSalidas Gráficas en la Ventana gráficas ( por ejemplo mapa proyecciones). Para entender cómo IDL posiciona gráficas, es importante comprender un poco mas las definiciones. La posición gráficaes la ubicación en la ventana mostrada que es adjunto por los ejes de la gráfica. La posición gráfica no incluye el etiquetado de los ejes, títulos, o otras anotaciónes (Véase a continuación la Figura 26 ). La región gráfica es la porción de la Ventana de visualización que incluye la gráfico posición, pero también incluye el espacio alrededor del gráfico posición para tal cosas como etiquetar ejes, graficas y títulos de los ejes, etcétera. El margen gráfico es definida como la área en la que se muestra la

ventana que es no la gráfica de posición.

El gráfico de posición puede ser establecido por un sistema variable ! P.Position o por la Palabra clave Position para los comandos Plot, Surface, Contour, o cualquier otro comando gráfico IDL.

Page 28: Coyote Traduction

Positiorzing Gt.aplzic Ozctpzct in tlze Display Window

Graphic Margin

I I Figzcre 26: The graphic positiorz is tlze area of tlze display erzclosed by the axes of the

graphic. The graphic region is sirttilar, but also corztairzs space for the graplzic's titles and other artrzotatiorz. The graphic margin is jzcst tlze op- posite of the graphic positiorz. The graphic margin is specified iiz char- acter z~rzits, whereas the graphic position alzd graphic region are specified irz norinalized coorditzate zcnits.

The entire graphic region may be set by the !P.Regiorz system variable, or regions on individual axes can be set using the Regioiz field to the !X, !k: and !Z system variables. The graphic margins may be set by the [XYZIMnrgirz keywords to the Plot, Surfice, Corztoui; or other IDL graphics command or by the Mnrgi1.1 field in the !X, !I: and !Z system variables.

By default, IDL sets the graphic margin when it tries to put a graphic into the display window. But, as you will see, that is not always the best choice. It is sometimes better to use the graphic position to position your graphics displays, especially if you are combining graphics output commands in one display window.

Posicion Gráfica

Reguión Gráfica

Margen Gráfica

Figura 26: La gráfica de posición es la área mostrada adjuntada por los ejes del gráfico. La región gráfica es similar, pero también contiene espacio para títulos y otros anotaciones. El margen gráfico es justo lo opuesto de la posición gráfica. El margen gráfico es especificado en unidades de carácteres,mientras la posición gráfica y región gráfica son especificado en unidades coordenadas normalizadas.

Toda la región gráfica puede ser establecida por el sistema variables ! P.Region , o regiones enejes individuales puede ser establecido mediante el campo de la región del sistema variables !X, !Y, y !Z. El márgen gráfico puede ser establecido por la palabras clave [XYZ]Margin para los comandos Plot, Surface, Contour; o otros comandos gráficos IDL o por el campo de margenes del sistema variable !X, !Y, y !Z.

Por defecto, el conjunto de margen gráfico IDL cuando intenta poner un gráfico en la ventana de visualización. Pero, como usted visualiza, que no es siempre la mejor elección. A veces es mejor utilizar la gráfica de posición para posiciónar su gráficos en pantalla, especialmente si usted combina gráficos de salida con los comandos en la ventana de visualización.

Page 29: Coyote Traduction

Sin~ple Graphical Displays

Setting the Graphic Margins The graphic margins can be set with the [XYZIM~J-gin keywords in the graphics command or by setting the Margirz field of the !X, !X and !Z system variables. What is unusual about the graphic margins is that the units are specified in terms of character size. The X margin is set by a two-element vector specifying the left and right offsets, respectively, of the axes from the edge of the display. The Y margin specifies the bottom and top offsets in a similar way. The default margins are 10 and 3 for the X axis and 4 and 2 for the Y axis. To see what the current character sizes are in device or pixel units, type:

IDL> Print, !D.X-Ch-Size, !D.Y - Ch-Size

On a Macintosh, for example, the default character size is 6 pixels in X and 9 pixels in Y. Thus, a contour plot is drawn with (6 times 10) 60 pixels on its left edge of the plot and (6 times 3) 18 pixels on its right edge. If the ChalSize keyword is set to 2 on a Contour command, for example, then there will be 120 pixels on the left edge of the plot and 36 on the right edge.

For example, to change the graphic margins to three default character units all the way around the plot, you would type:

IDL> Plot, time, curve, margin= [3,3] , margin= [3,3]

Notice, however, that the plot looks very different if you also change the character size, since graphic margins are specified in terms of character size. Try this:

IDL> !X.Margin = [3,3] DL> !Y. Margin = [3,31 IDL> Contour, peak, CharSize=2 . 5 IDL> Contour, peak, CharSize=l . S

If you play around a bit with other character sizes, you can see that at larger character sizes, the characters get very large and the graphics portion of the plot gets very small. This is not always what you want.

Be sure to set the graphic margins back to their default values before you move on. Type:

Unlike many other system variables, whose values are set back to the default values by setting the system variable equal to 0, the margin system variables must be set explicitly to their default values. If you didn't type the two commands above, be sure to do it now.

Setting the Graphic Position Setting the graphic position requires setting a four-element vector giving, in order, the coordinates [XO, YO, XI, Y l ] of the lower-left and upper-right corners of the graphic in the display window. These coordinates are always expressed in normalized units ranging from 0 to 1 (i.e., 0 is always either the left or the bottom of the display window, and 1 is always either the right or top of the display window).

For example, suppose you wanted your graphic output to be displayed in the top half of the display window. Then you might set the !P.Positioiz system variable and display your graphic like this:

IDL> !P.Position = L0.1, 0.5, 0.9, 0.91 IDL> Plot, time, curve

Ajustando los Márgenes GráficosLa gráfico márgenes puede ser establecida con la palabras clave [XYZ]Margin en el comando gráfico o por el ajuste del campo de Margenes del sistema de variables !X, !Y, y !Z. ¿Qué es inusual acerca de los márgenes gráficos que las unidades son especificadas en condiciones del tamaño de la fuente (CaharSize). El margen X es especificando por un vector de dos elementos a la izquierda y derecho, respectivamente, de los ejes de borde para mostrar. El margen Yespecifica la compensaciones para la parte inferior y superior de manera similar. El defecto de márgenes son 10 y 3 para la Eje X y 4 y 2 para el eje Y. Para ver qué el tamaño de caracteres corra debe de estar enen unidades de pixel, tipo:

En una Macintosh, por ejemplo, el carácter de tamaño por defecto es 6 píxeles en X y 9 píxeles enY. Por lo tanto, un contorno grafico es dibujado con (6 veces 10) 60 píxeles en su borde izquierda de la gráfica y (6 veces 3) 18 píxeles en su borde derecho. Si la palabra clave CharSize es establecida a 2 en un comando contour, por ejemplo, entonces ayi hay 120 píxeles en la borde izquierdo de la trama y 36 en la derecho borde.

Por ejemplo, para cambiar los márgenes gráficos a tres unidades de carácteres por defecto todo el camino alrededor del gráfico, usted haría lo siguiente:

Notese, Sin embargo, que la gráfica parece muy diferente si cambiamos el tamaño de la fuente, los márgenes gráficos son especificados en condiciones del tamaño del carácter. Prueba esto:

Si usted jugar alrededor de un bit con otro tamañode carácter, usted puede ver que en mayor tamaños de caracteres,el caracter conseguido es muy grande y la porción gráficas de la pantalla es muy pequeña. Este es no Siempre lo que desea.

Asegúrese a establecer los márgenes gráficos detras de su valores por defecto antes usted sigaadelante. Tipee:

Desasemeja muchas otras variables del sistema, cuyo valores son establecer antes los valorespor

defecto ajustando el sistema de variable igual a 0, el margen del sistema variables debe ser establecidoexplícitamente a valores por defecto. Si usted no lo hizo tipee los dos comandos por encima de snow.

Ajustando la Posición Gráfica Ajustando la posición gráfica requiere dar un ajuste en cuatro vectores de elementos , en orden, las coordenadas [X0, Y0, X1, Y1] de la izquierda inferior y la esquinas superior derecha del gráfico a mostrar. Estas coordenadas son siempre expresadas en unidades normalizadas que van de 0 a 1 (Es decir, 0 es siempre la izquierda o el fondo de la ventana mostrada, y 1 es siempre la derecha o superior de la ventana mostrada).

Por ejemplo, suponer usted deseado su salida gráfica ser desplegado en el medio superior de la ventana mostrada. Entonces usted fuerza la variable del sistema con ! P.Position y mostre su gráfico como esto:

Page 30: Coyote Traduction

Positiorziizg Graphic Ozitplct in the Display Wii~do~v

All subsequent graphics output will be positioned similarly. To reset the !R Position system variable so that subsequent graphic output fills the window normally, type:

If you wanted to position just one graphic display, you could specify a graphic position with the Position keyword to the graphics command. Suppose you wanted a contour plot to just fill up the left-hand side of a display window. You might type this:

IDL> Contour, peak, position= [O.l, 0.1, 0.5, 0.91

Note that the Positiolz keyword can be used to put multiple graphics plots into the same display window. Just be sure to use the NoEl-ase keyword on the second and all subsequent graphics commands. This will prevent the display from being erased first, which is the default behavior for all graphics output commands except TV and TVScl. For example, to put a line plot above a contour plot, you can type:

IDL> Plot, time, curve, ~osition=[O.l, 0.55, 0.95, 0.951 IDL> Contour, peak, ~osition=[~.l, 0.1, 0.95, 0.451, / ~ o ~ r a s e

Setting the Graphic Region The graphic region is specified in normalized coordinates in the same way as the graphic position, and can be specified by setting the !PRegiorz system variable. Since there is not an equivalent keyword that can be set on a graphics command, setting the graphics region is often less convenient than setting the graphics position. Be sure you reset the system variable if you want subsequent plots to use the whole display window normally. For example, to display a plot in the upper two-thirds of your display window, type:

IDL> !P.Region = [0.1, 0.33, 0.9, 0.91 IDL> Plot, time, curve

To reset the !PRegiorz system variable so that subsequent plots fill the window normally, type:

IDL> ! P. Region = 0

Creating Multiple Graphics Plots As you can see, multiple plots can be positioned on the display using the graphic position and graphic region system variables and keywords discussed above (as long as the second and all subsequent plots use the NoErase keyword). But it is much easier to use the !RMulti system variable to create multiple plots on the display. !RMulti is defined as a five element vector as follows:

!P.Multi[O] The first element of !PMulti contains the number of graphics plots remniizing to plot on the display or Postscript page. This is a little non-intuitive, but you will see how it is used in a moment. It is normally set to 0, meaning that as there are no more graphics plots remaining to be output on the display, the next graphic command will erase the display and start with the first of the multiple graphics plots.

This element specifies the number of graphics columns on the page.

This element specifies the number of graphics rows on the page.

This element specifies the number of graphics plots stacked

in the Z direction. (This applies only if you have established a

3D coordinate system.)

Toda salida gráfica posterior puede ser posicionado de manera similar. Para reajustar la variable

del sistema ! P.Position posterior a la gráfica de salida de la ventana normalmente, tipee:

Si usted queria posiciónar sólo uno pantalla gráfica, usted podría especificar un posición gráfica

con la palabra clave Position con el comando graphics. Supongo que usted a deseado sólo un contorno gráfico lleno hasta el lado izquierdo de una ventana mostrada. Usted puede tipear esto:

Nota que la palabra clave Position puede ser utilizado para múltiples gráficos en lo mismo ventana de visualizacion. Sólo este seguro a utilizar la palabra clave NoErase y todas las posteriores comandos gráficos . Usted evitar borrar primero la ventana de visualizacion, el cual es por defecto el comportamiento para todo gráfico salida excepto los comandos TV y TVScl. Por ejemplo, para mostrar una línea gráica arriba con un contorno gráfico, usted puede tipear:

Ajuste la Región GráficaLa región gráfico es especificada en coordenadas normalizadas de la mismo manera como laPosición gráfica , y puede ser especificado ajustado por la variables sistema ! P.Region . Puesto que no hay una palabra clave equivalente que pueda ser establecer en un comando gráfico,ajustar las regiónes gráficos a menudo menos conveniente de ajustar las posiciónes gráficas. Usted puederesetear las variables sistema si usted quiere posteriormente gráficas a utilizar toda Ventana de visualización normalmente. Por ejemplo, mostrar una gráfica superior con los dos tercios de la ventana de visualización , tipo:

Para reajustar las variables del sistema use la palabre clave !P.Region así posteriormente el llenado gráfico de la ventana es normal, tipee:

Creando Múltiples GráficasComo usted puede ver, puede posicionar múltiples graficas y región gráfica de las variables del sistema y palabras claves discutidas (Como siempre cuando el segundo y el posterior grafico utilizan la palabra clave NoErase ). Pero es mucho más fácil utilizar la ! P.Multisistema variable a crear varias graficas a mostrar. ! P.Multi se define como cinco vectores de elemento como son los siguiente:

El primero elemento de ! P.Multi contiene el número de parcelas gráficos restante para mostrar o paginas PostScript. Esto es un poco no intuitivo, pero usted pede ver cómo lo esta utilizado en un momento. Es normal establecerlo a 0, significando que allí no hay más parcelasgráficas restante a ser mostradas en la salida, el siguiente comando gráfico borra la pantalla e inicia con la primera parcela gráfica múltiple.

Este elemento especifica la número de gráficos columnas en el página.

Este elemento especifica la número de gráficos filas en la página.

Este elemento especifica la número de parcelas gráficos apilados en la dirección Z . (Esta aplica sólo si usted tiene establecido un sistema de coordenadas 3D.)

Page 31: Coyote Traduction

Sil?zple Graphical Displays

!P.Multi[cl] This element specifies whether the graphics plots are going be displayed by filling up the rows first (!P.Mzrlti[4]=0) or by filling up the columns first (!PMulti[4]=1).

For example, suppose you want to set !Z?M~llti to display four graphics plots on the display in two columns and two rows, and you would like the graphics plots to fill up the columns first. You would type:

Now as you display each of the four graphics plots, each graphic fits into about a quarter of the display window. Type:

IDL> Window, XSize=500, YSize=500 IDL> P l o t , t ime, curve, LineStyle=O IDL> Contour, peak, lon , l a t , XStyle=l , YStyle=l, NLevels=lO IDL> Surface, peak, lon , l a t IDL> Shade-Surf, peak, lon, l a t

Your output should look similar to the output in Figure 27.

Figzcre 27: You caiz plot multiple graphics plots iiz a siitgle display wiitdow.

Leaving Room for Titles with Multiple Graphics Plots When IDL calculates the position of the graphics plots, it uses the entire window to determine how big each plot should be. But sometimes you would like to have extra

Este elemento especifica si las parcelas gráficss van a ser desplegadas por fila y rellenadas primero (! P.Multi [ 4] = 0) o primero llenando la columnas (! P.Multi [4] = 1).

Por ejemplo, suponer que usted quiere establecer un ! P.Multi a mostrar cuatro parcelas gráficos en la pantalla en dos columnas y dos filas, y usted haría que la parcelas gráficos a llenar primero sean las columnas . Usted puede tipear esto:

Ahora como usted mostra cuatro parcelas gráficos, cada gráfico se ajusta en cuarto de ventana de visualización. Tipee:

Su salida debería ser similar a la salida en Figura 27.

Figura 27: Usted puede graficar múltiples parcelas en una solo ventana de visualización.

Dejando Espacio para Títulos con Múltiple Parcelas Gráficos Cuándo IDL calcula la posición de las parcelas gráficas, utiliza toda ventana para determinar cuan grande debería ser cada parcela. Pero a veces usted le gustaria tener espacio extra para mostrar

Page 32: Coyote Traduction

Positiortiitg Graphic Outpzct in the Display Window

room on the display for titles and other types of annotation. You can leave room with multiple plots by using the "outside margin" fields of the !X, !t: and !Z system variables. The outside margins only apply when the !l?Mzrlti system variable is

being used. They are calculated in character units, just as the normal graphic mara' ulns are calculated.

For example, suppose you wanted to have an overall title for the four-graphic plot display you just created. You might leave room for the title and create it like this:

IDL> !P.Multi = 10, 2, 2, 0, l] IDL> !Y .OMargin = [2, 41 IDL> Plot, time, curve, LineStyle=O IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, NLevels=lO IDL> Surface, peak, lon, lat IDL> Shade-Surf , peak, lon, lat IDL> XYOutS, 0.5, 0.9, /Normal, 'Four Graphics Plots1, $

Alignment=0.5, Charsize=2.5

Your output should look like the illustration in Figure 28.

Four Graphics P lo ts

Figure 28: A four by four multiplot with space left at the top of the plot for a title by using the !Y.OMargiiz keyword.

títulos y otro tipos de anotación. Usted puede dejar espacio para el uso de "margen externos " campos del sistema de variables !X, !Y, y !Z . Los márgenes externos sólo se aplican cuando la variable del sistema ! P.Multi . Ellos son calculados enunidades de carácteres, sólo con los márgenes de gráfico normales calculados.Por ejemplo, supongo que usted desea tener un título total para las cuatro gráficas creadas. Usted puede dejar espacio para el título y crearlo como esto:

Su salida debería ser como la ilustración en Figura 28.

Figura 28: Un cuadro de cuatro gráficos múltiples con espacio izquierda en la parcela superior para un título mediante el uso de la palabra clave ! Y.OMargin.

Page 33: Coyote Traduction

Siirzple Grapltical Displays

Non-Symmetrical Arrangements with !P.Multi Plotting with !l?Multi does not have to be symmetrical on the display. For example, suppose you wanted the surface and shaded surface plot in the left-hand side of the display window one above the other, And you wanted the right-hand side of the page to be filled with a contour plot of the same data. You can type this code:

IDL> !P.Multi = [O, 2, 2, 0, 11 IDL> !Y.OMargin= [0, O] IDL> Surface, peak, lon, lat IDL> Shade-Surf , peak, lon, lat IDL> !P.Multi = [l, 2, 1, 0, 01 IDL> Contour, peak, lon, lat, XStyle=l, YStyle=l, NLevels=lO

The first !F!Multi command sets up a two-column by two-row configuration and the first two of these plots are drawn. The second !l?Multi command sets up a two- column by one-row confiouration. But notice that !l?Mulfi[O] is set to l. This results P in the contour plot going Into the second position in the window instead of the first. The result is shown in Figure 29, below.

Figzcre 29: You can use !P.Multi to position asymmetric arraitgements of plots irt the display window.

Note that the TV command does not work with !Z?Multi like the Plot or Contour com- mands do. However, the TVInzage program, which is a replacement for the TV com-

Argumentos No Simétricos con !P.MultiEl graficado con !P.Multi no hace simétrico la grafica. Por ejemplo, supongamos que usted desea la superficie y la superficie sombreado en la parcela izquierda al lado de la ventana de visualización. Y usted desea que el lado derecho de la página sea llenado con un contorno gráfico de los mismo datos. Usted puede tipear este código:

El primer comando ! P.Multi con dos columnas por de dos hileras con figuración y estas dos primeras parcelas son dibujadas. El segundo comando ! P.Multi con Dos columna y una fila de configuración. Pero notar que ! P.Multi [0] se establece a 1. Este resultado en la gráfica de contorno puede ir en la segunda posición en la ventana en lugar de la primera. El resultado se muestra en Figura 29, a continuación.

Figura 29: Usted puede utilizar ! P.Multi para posiciónar arreglos asimétricos de parcelas en laventanade visualización.

Nota que el comando TV no funciona con ! P.Multi los comandos Plot o Contour. Sin embargo, el programa TVImage, renplaza al comando TV y esta entre los programas que usted ha descargado para utilizar con este libro, hace satisfacer la variable del sistema ! P.Multi .

Page 34: Coyote Traduction

Addiizg Text to G1*apltical Displays

mand and is among the programs you downloaded to use with this book, does honor the !P.Mzrlti system variable. Try these commands:

IDL> image = LoadData ( 7 ) IDL> !P.Multi=[O, 2 , 21 U)L> FOR j = 0 , 3 DO TVImage , image

Be sure you reset !l?Mzrlti to display a single graphics plot on the page. Like many system variables, !P.Mzrlti can be reset to its default values by setting it equal to zero, like this:

Adding Text to Graphical Displays Plot annotations and other text can be added to graphical displays in a variety of ways, the most common of which is via keywords to graphical display commands. The text that is added can come in any of three font "flavors" or styles, if you like: vectol. forzts (sometimes called software or Hershey fonts), true-type fonts, and hnrdtvnre fonts. The type of font is selected by setting the !Z?Fo~zt system variable or by setting the Font keyword on a graphical output command according to Table 6, below.

Table 6: Tlze font "Jlavor" cart be selected by setting the !R Foitt system variable or the Foizt keyword to the appropriate value. Vector fonts are the default font type for direct graphics commaitds. They have the advaittage of being platform irtdeperzde~tt.

By default fonts in direct graphics routines are set to the vector or software font style. Vector fonts are described by vector coordinates. As a result, they are platform independent and can be rotated in 3D space easily. However, many people find vector fonts too "thin" for quality hardcopy output and prefer more substantial fonts for this purpose (i.e., true-type fonts or Postscript hardware printer fonts). Vector fonts can be selected permanently by setting the !P.Forzt system variable to -1 or by setting the Forzt keyword on a graphical output command, like this:

IDL> Plot, time, curve, Font=-l, XTitle=lTime', $ YTitle='Signall, Title=IExperiment 35F3a1

True-type fonts are also called outline fonts. The font is described by a set of outlines that are then filled by creating a set of polygons. IDL comes with four true-type font families: Times, Helvetica, Courier, and Symbol, but you can supplement these with any other true-type font family you have available. True-type fonts take longer to render because the font must be scaled and the polygons created and filled, and many people find them a bit unattractive at small point sizes on normal low-resolution displays. But they have the great advantage of being rotatable and nice looking on hardcopy output devices. True-type fonts are the default font for the object graphics system in IDL.

To render a plot with the default me-type Helvetica font face, set the Font keyword to 1, like this:

Intentar estos comandos:

Estar seguro de reajustar ! P.Multi para mostrar un sola parcela gráfica en la página. Como muchos sistemas las variables, ! P.Multi pueden ser reajustadas por valores por defecto igual a cero, al igual que esto:

Agregando Texto para Mostrar GráficosLa parcela de anotaciones y otro textos pueden ser adicionadas a la pantalla gráfica en un variedad .de maneras, la más común de las palabras clave es el comando gráfico mostrar. El texto que es

adicional puede venir en cualquier de tres fuente "flavors" o estilos, a usted le recomendamos: el vector fuente (a veces llamado software o fuentes Hershey), fuentes true-type, y fuentes hardware. Los tipos de letra, tipo de fuente es seleccionado por el ajuste las variables del sistema !P.Font o por la palabra clave Font en un comando gráfico de salida conforme a Tabla 6, a continuación.

Tabla 6: La Fuente '' flavor " puede ser seleccionado ajustando las variable del sistema ! P.Font o la palabra clave Font para valores apropiados. El vector fuente son Tipos de fuentes por defecto para comandos gráficos directos. Ellos tienen la ventaja de ser plataforma independientes.

Vector Fuente

Fuente Hardware

!P.Font Selección de Fuente

Las fuentes de contorno de tipo verdadero

(también las fuentes llamadas software o Hershey)

Las fuentes por defecto en rutinas gráficas directas son establecen el estilo del vector fuente o software . El vector Fuentes es descrito por vector de coordena. Como consecuencia, de la plataforma independiente y puede ser fácilmente girada en el espacio 3D. Sin embargo, muchas personas encuentran fuentes vectoriales "Delgadas" para calidad la salida impresa y preferir fuentes sustancial para este propósito (Es decir, fuentes de tipo verdadero o fuentes hardware para impresión PostScript). El vector fuentes puede ser seleccionado permanentemente por la variable del sistema ! P.Font a -1 o por ajustando la palabra clave Font en un gráfico salida,como esto:

El tipo de fuentes son también llamado fuentes perfiladoras . La fuente es descrito para establecer un esquemas de llenado para la creación de un polígono. IDL viene con cuatro familias de fuentes true-type: Times, Helvetica, Courier, y Symbol, pero usted puede complementar estos con cualquier otra familia de fuente true-type que usted tenga disponible. Las Fuentes True-type deben ser escalas y los polígonos creados y llenados, muchas personas encontran en ellos un bit no atractivos para pequeños tamaños de puntos en la pantalla normal de baja resolución. Pero ellos tienen la ventaja de ser giratorios y bonitos en la salida del dispositivos de impresión. Las fuentes True-type son por defecto fuentes para objeto en el sistema de gráficos IDL.

Para hacer un parcela con fuente true-type Helvetica por defecto, establecer la palabra clave Font a 1, como esto:

Page 35: Coyote Traduction

Siinple Graplzical Displays

IDL> Plot, time, curve, Font=l, XTitle='Timel, $ YTitle='Signall, Title='Experiment 35F3a1

True-type fonts can be selected with the Device command using the Set-Font and 'IT_Forzr keywords, like this:

IDL> Device, Set-F~nt=~Courier~, /TT Font IDL> Plot, time, curve, Font=l, ~ ~ i t i e = Time , $

YTitle='Signal', Title='Experirnent 35F3a1

To learn more about true-type fonts in IDL, use your on-line help system like this:

IDL> ? fonts

Hardware fonts are selected by setting the !P.Font system variable or the Forzt keyword to 0. Normally hardware fonts are not used on the display, but are used when output is sent to a hardcopy output device such as a Postscript printer. Unfortunately, hardware fonts do not rotate well in 3D space and so were not normally used with 3D commands like the Surface command.

IDL> Plot, time, curve, Font=O, XTitle='Timel , $ YTitle='Signall, Title='Experirnent 35F3a1

Finding the Names of Available Fonts You can find the names of available hardware fonts by using the Device command like this:

IDL> Device, Font='*', Get-FontNames=fontnames IDL> For j =0, N-Elements (f ontnames) -l DO print, f ontnames [j 1

The names of true-type fonts are found in a similar way, except that the TT'Folzr keyword is used to select just the available true-type fonts on your system. (You can add your own true-type fonts to the four families supplied with IDL. See the IDL on- line help to find out how.)

IDL> ~evice, Font=I*l, Get-FontNames=fontnames, / T T - F O ~ ~ IDL> For j = O ,N-Elements (f ontnames) -l DO print, f ontnames [j]

The names of available vector fonts are given in Table 7 on page 53.

Adding Text with the XYOutS Command A very important command in IDL is the XYOutS command ("at an XY location, OUTput a String"). It is used to place a text string at a specific location on

the display. (The first positional parameter to XYOutS is the X location and the second positional parameter is the Y location). For example, to add a larger title to a line plot, you can type commands like this:

IDL> Plot, time, curve, Position=[0.15, 0.15, 0.95, 0.851

IDL> XYOutS, 0.5, 3 2 , 'Results: Experiment 35F3a1, Size=2.0

Notice that you specified the X and Y location with data coordinates. Also notice that the Y coordinate is outside the boundary of the plot. By default, the XYOutS procedure uses the data coordinate system, but the device and rzorr~zalized coordinate systems can also be used if the appropriate keywords are specified.

(The data coordinate system is, naturally, described by the data itself. Device coordinates are sometimes called pixel coordinates and the device coordinate system is often used with images. A normalized coordinate system goes from 0 to 1 in each direction. Normalized coordinates are often used when you want device-independent graphics output.)

El tipo de fuente verdaderas puede ser seleccionado con el comando Device usando la palabras clave Set_Font y TT_Font , como esto:

Para saver más acerca de Fuentes tipo verdadero utilice el sistema de ayuda en IDL, como esto:

Las Fuentes Hardware son seleccionados por la variables del sistem ! P.Font o la Palabra clave Font a 0. Normalmente las Fuentes hardware no son utilizadas en la ventana, pero son utilizado cuando la salida es enviado a un dispositivo de salida impresa tal como un impresión PostScript.Por desgracia, las fuentes de hardware no giran bien el espacio 3D y entonces eran no utilizados normalmente con los Comandos 3D como el comando Surface.

Descubriendo el Nombre del Disponible FuenteUsted puede encontrar los nombres disponible de las Fuentes hardware usando el comando

Device como esto:

Fuentes del tipo verdadero son similares, excepto la Palabra clave TT_Font que es utilizado para seleccionar sólo la Fuentes disponible true-type en su sistema. (Usted puede agregar su propia Fuentes true-type a la cuatro familias suministrada con IDL. Ver la ayuda online de IDL) cómo:

Los nombres disponible de las fuentes vectoriales son dados en Tabla 7 en página 53.

Agregando Texto con el Comando XYOutS Una muy importante comando en IDL es XYOutS ("En un lugar XY, la Cadena OUTput "). Esto es usado para dar lugar a una cadena de texto para un lugar específico en la ventana. (La primera posicion del parámetro XYOutS es la ubicación X y la segunda posicion del parámetro es la ubicación Y ).Por ejemplo, para añadir un título largo para una línea gráfica, usted puede escribirlos comandos como esto:

Notar que usted a especificado la ubicación con datos de coordenadas X e Y. También notar que la coordenada Y es fuera del límite de la gráfica. Por defecto,el procedimiento de XYOutS utiliza los datos coordenados del sistema, y las coordenadas normalizadas sistemas también pueden ser utilizados si son especificado con la palabras clave.

(Los datos del sistema de coordenadas es decir, naturalmente, descrito por la datos en sí. La Coordenada son a veces llamadas coordenadas de pixeles y el sistema de coordenadas es a menudo utilizado con imágenes. La normalización del sistema de coordenadas va de 0 a 1 en cada dirección. La Normalización de coordenadas son a menudo utilizado cuando usted quierer gráficar imagenes independientes en el dispositivo de salida.)

Page 36: Coyote Traduction

Adding Text to Graphical Displays

For example, you can put the title on the line plot using rzounnlized coordinates, like this. When you are writing IDL programs it is often a good idea to specify things like titles and other annotation with normalized coordinates. This makes it easy to place graphics not only in the display window, but in Postscript and other hardcopy output files as well.

IDL> Plot, time, curve, Position= [0.15, 0.15, 0.95, 0.851 IDL> XYOutS, 0.2, 0.92, 'Results: Experiment 35F3a1, $

Size=2.0, /Normal

Table 7: The Hershey fonts with correspo~tdirzg index rzuntber used to select them within ZDL.

! 7

!8

! 9

! 10

!l1

Using XYOutS with Vector Fonts The XYOcltS command can be used with either vector, true-type, or hardware fonts. Simply set the appropriate Font keyword value as described above. The discussion here concerns itself with vector fonts, since that is the font system that is most often used in direct graphics commands. A list of the available vector fonts along with the index numbers you use to specify the specific font is given in Table 7.

Complex Greek

Complex Italian

Math Font

Special Characters

Gothic English

The major advantage of vector or Hershey fonts, is that they are platform independent and can be scaled and rotated in 3 0 space. For example, you can write the plot title above in Triplex Roman characters by typing:

IDL> Plot, time, curve, Position=[0.15, 0.15, 0.95, 0.851

IDL> XYOutS, 0.2, 0.92, '!17Results: Experiment 35F3a!X1, $ Size=2.0, /Normal

The Triplex Roman characters were specified with the !l 7 escape sequence. The !X at the end of the title string caused the font to revert back to the Simplex Roman font that was in effect before you changed it to Triplex Roman. This reversion step is important because otherwise the default font gets set to Triplex Roman and all subsequent strings will be set with Triplex Roman characters. For example, try using a Greek character

as

the X title of the plot and try writing the plot title like this:

!l6

! 17

! 18

!20

!X

IDL> Plot, time, curve, XTitle=' !7w1, $ Position=[0.15, 0.15, 0.95, 0.851

IDL> XYOutS, 0.2, 0.92, 'Experiment 35F3X1, Size=2.0,

/Normal

Cylillic

Triplex Roman

Ti-iplex Italian

Miscellaneous

Revert to entry font

You can see the results in Figure 30. Notice that now, even though you

didn't specify that it should be so, the title is written in Greek characters. The only way to make it

Por ejemplo, usted puede poner el título en la línea gráfica usando coordenadas normalizadas, de esta manera. ¿Cuándo usted escriba programas en IDL una buena idea es especificar cosas como títulos y otro anotación con coordenadas normalizada. Esto lo hace fácil a lugar de gráficos no sólo en la ventana de visualización, pero en PostScript y otros archivos de salida de impresión como esto.

Tabla 7: La fuente Hershey con correspondiente números índice para ser utilizado dentro IDL.

Número NúmeroDescripción Descripción

Usando XYOutS con Vector FuentesEl comando XYOutS puede ser utilizado con vector true-type, o fuentes hardware. Simplemente estableciendo la adecuada palabra clave font con valor descrito anteriormente. La discusión con el vector fuente, es decir la fuente del sistema que es más utilizado a menudo en comandos gráficos. La lista de la disponible vector Fuentes con los números índice se utiliza esta dado en Tabla 7.

La mayor ventaja del vector fuente Hershey, es que ellos son plataforma independiente y pueden ser escaladas y girardas en El espacio 3D. Por ejemplo, usted puede escribir la parcela de título anterior en Triple Romano escribiendo:

E Triplex Roman era especificado con la secuencia de escape !17. La !X al final de la cadena de título causaque la fuente a revertir detras de la fuente Simplex Romano que fue antes cambiado a Triplex Roman. Esta reversión es un paso importante porque de otra manera la fuente por defecto sigue establecida a Triple Romano y todo sera establecido posteriormente a Triplex romana. Por ejemplo, intentar uso un Carácter griego como la parcela de titulo X e intentar escrivir la parcela título como esto:

Usted puede ver el resultado en Figura 30. Notar que ahora, incluso aunque usted no lo hizo especificado que lo debería ser así, el título es escrito en Griego. Sólo manera a hacer lo

Page 37: Coyote Traduction

Sii~zple Graphical Displays

revert back to the default Simplex Roman is write another string with explicit Simplex Roman characters. For example:

IDL> XYOutS, 0.5, 0.5, !3Junk1, /Normal, Charsize=-l

Notice the use of the ClznrSize keyword in the code above. When this keyword has a value of - 1, the text string is suppressed and not written to the display.

Figure 30: Be careful when yozc select a Hershey font, oryou might end z c g with plot titles that look like Greek to yozcr users.

Aligning Text You can position text with respect to the location specified in the call to XYOutS with the Aligrzrnei~t keyword. A value of 0 will left justify the string (this is the default case); a value of l will right justify the string; and a value of 0.5 will center the string with respect to the location specified by the X and Y values. For example:

IDL> Window, XSize=300, YSize=250 IDL> XYOutS, 150, 55, 'Research1, Alignment=O.O, $

/Device, CharSize=2.0 IDL> XYOutS, 150, 110, 'Research', Alignment=0.5, $

/Device, CharSize=2.0 IDL> XYOutS, 150, 170, 'Research1, Alignment=l.O, $

/Device, CharSize=2.0 IDL> Plots, [0.5, 0.51, [1.0, 0.01, /~ormal

Erasing Text Text that is written with XYOutS can sometimes be "erased" by writing the same text over in the background color. The Color keyword in conjunction with the !P.Bnckgrouizd system variable is used for this purpose. Note that this only works perfectly if the text was written on nothing but the background! There are often other,

better methods to erase annotations. (See "Erasing Annotation From the Display" on page 114, for example.) To see how to erase annotation with the background color, type this:

IDL> Window, XSize=300, YSize=250 IDL> XYOutS, 150, 110, 'Researchv, Alignment=0.50, $

/Device, CharSize=2.0 IDL> XYOutS, 150, 110, 'Research1, Alignment=0.50, $

/Device, CharSize=2.0, Color=!P.Background

volver a la simplex roman es escribir otra cadena con Caracteres romanos explícitos Simplex.Por ejemplo:

Observe el uso de la palabra clave CharSize en el código anterior. Cuando esta palabra clave tiene unvalor de -1, la cadena de texto se suprime y no se escribe en la pantalla.

Figura 30: Ser cuidadoso cuando usted Selecciona la fuente Hershey, o usted fuerze al final con trama de título Griego para sus usos.

Alineando TextoUsted puede posiciónar texto con respeto a la ubicación llamando a XYOutS con la palabra clave Alignment a un valor de 0 justificando la cadena a la izquierda (Este es la caso por defecto); un valor de 1 justifica la cadena a la derecha; un valor de 0.5 centro la cadena con respeto a la ubicación especificado por los valore X e Y. Por ejemplo:

Borrando Texto

El Texto escrito con XYOutS puede a veces ser "Borrado" por el mismo color de fondo. La palabra clave Color en conjunción con el sistema de variable !P.Background es utilizado para este propósito. Nota que este sólo funciona perfectamente si la texto era escrito en el fondo,otro método mejor para borrar anotaciones. (Ver "Borrado Anotación De lMuestra " en la página 114), por ejemplo cómo borrar una anotación con el color de fondo, tipee esto:

Page 38: Coyote Traduction

Adding Text to Grapltical Displays

Orienting Text The text specified with the XYOutS command can be oriented with respect to the horizontal with the Orieiztation keyword, which specifies the number of degrees the text baseline is rotated away from the horizontal baseline. For example, type:

IDL> Window, XSize=300, YSize=250 IDL> XYOutS, 150, 110, 'Research', Alignment=0.50, $

/~evice, CharSize=2.0, Orientation=45 IDL> XYOutS, 150, 180, 'Research1, Alignment=0.50, $

/~evice, CharSize=2.0, Orientation=-45

Positioning Text IDL also provides a number of ways to position and manipulate text in graphical displays. For example, it is possible to create subscripts and superscripts in a plot title. Text positioning is accomplished by means of embedded positioning commands, as shown in Table 8, below.

Table 8: The embedded commands that cart accomplish textpositioitiizg in strings. These are often used to produce subscripts and superscripts Lz plot titles, for example.

For example, an equation can be written like this:

IDL> XYOutS, 0.5, 0.5, /~ormal, Alignment=0.5, Size=3.0, $ 'Y = 3X!U2!N + 5x + 3'

Orientando el TextoEL texto especificado con el comando XYOutS puede ser orientado con respeto a la horizontal con la palabre clave Orientation, que especifica la número de grados queel texto base va ha girar lejos de la línea horizontal de base. Por ejemplo, tipee:

Posicionamiento del Texto

IDL también proporciona un número de formas de posición y manipulación de texto en pantallas gráficas. Por ejemplo, es posible crear subíndices y superíndices en un parcela de título. EL posicionamiento del texto es logrado por medio de comandos de posicionamiento, como se muestra en Tabla 8, a continuación.

menudo utilizado para producir subíndices y superíndices en la parcela de títulos,

Por ejemplo, un ecuación puede ser escrito como esto:

Tabla 8: Los comandos que pueden lograr el posicionamiento del texto. Estos son a

por ejemplo.

Comandos Acción del comando

Cambie texto sobre la línea de división.

Cambie texto debajo de la línea de división.

Inserte un variable deretorno y comience una nueva línea del texto.

Cree un subíndice de primer nivel.

Cree un índice sobrescrito de primer nivel.

Cree un subíndice de tipo de índice

Cree un subíndice de segundo nivel.

Cambio de vuelta al nivel normal después de cambiar nivel.

Restare la posición de texto a última posición salvada.

Salve la posición actual de texto.

Cree un índice sobrescrito de tipo de índice.

Retorna a la fuente de entrada.(use después que la fuente cambie)

Muestre unos o más caracteres por su valor de unicode.

Muestre el signo de admiración !

Page 39: Coyote Traduction

Sintple Graphical Displays

Adding Lines and Symbols to Graphical Displays Another useful routine for annotating graphical displays is the PlotS command, which is used to draw symbols or lines on the graphic display. The PlotS command works in either two- or three-dimensional space.

To draw a line with the PlotS procedure, simply provide it with a vector of X and Y values that describe XY point pairs that should be connected. For example, to draw a baseline on the line plot from the point (0, 15) to the point (6, 15), type:

IDL> Window, XSize=500, YSize=400 IDL> Plot, time, curve IDL> xvalues = [O, 61 IDL> yvalues = [15, 151 IDL> PlotS, xvalues, yvalues, ~ine~tyle=2

Your output should look similar to the output in Figure 3 1, below.

Figure 31: Tlzis plot is annotated witlz a dashed line drawiz across its center witlz the PlotS commaitd.

The PlotS procedure can also be used to place marker symbols at various locations. For example, here is a way to label every fifth point in the curve with a diamond symbol.

IDL> TvLCT, [70, 255, 01, [70, 255, 2501, [70, 0, 01, 1 IDL> Plot, time, curve, Background=l , Color=2 IDL> index = IndGen ( 2 0 ) * 5 IDL> Plots, time [index] , curve [index] , PSym=4, $

Color=3, SymSize=2

The PlotS command can also be used to draw a box around important information in a plot. By combining the PlotS command with other graphics commands, such as XYOutS, you can effectively annotate your graphic displays. For example, like this:

IDL> TvLCT, [70, 255, 01, [70, 255, 2551, [70, 0, 01, 1 IDL> Device, Decomposed=O IDL> Plot, time, curve, Background=l, Color=2 IDL> box-X-coords = [O .4, 0.4, 0.6, 0.6, 0.4 l IDL> box-y-coords = [0.4, 0.6, 0.6, 0.4, 0.41 IDL> Plots, box-X-coords, box-y-coords, Color=3, /Normal IDL> XYOutS, 0.5, 0.3, 'Critical Zone1, Color=3, Size=2, $

Alignment = 0.5, /Normal

Agregando Líneas y Símbolos al GráficoOtro rutina útil para anotaciones gráficas en pantallas es el comando PlotS, que es utilizado para dibujar símbolos o líneas en la gráfica. El comando Plots trabaja en cualquiera de los espacios bi o tridimensional.

Para dibujar un línea con la con el comando PlotS procure, simplemente proporcionar un vector de Valores X e Y que describen el par de puntos XY. Por ejemplo, dibujar una línea de base en la línea gráfica para el punto (0, 15) al punto (6, 15), tipee:

Su salida debería ser similar a la salida en Figura 31, a continuación.

Figura 31: La gráfica es anotado con un discontinua línea estirado a través de su centro con el comando PlotS.

El procedimiento del comando PlotS puede también ser utilizado para marcar símbolos en vario ubicaciones. Por ejemplo, aquí es un manera de etiquetar cada quinto punto en la curva con un rombo.

El comando PlotS puede también ser utilizado para dibujar un caja de importante información alrededor en una parcela. Combinando el comando PlotS con otro comandos de gráficos, tal como XYOutS, usted puede eficazmente anotar su pantallas gráfico. Por ejemplo, algo como esto:

Page 40: Coyote Traduction

Adding Color to Your Gi.aphical Displays

You can easily use the XYOzitS and PlotS commands to create legends for your graph- ics displays.

Adding Color to Your Graphical Displays Another useful way to annotate your gsaphical displays is to use color. The Polyfill command is a low-level graphic display command that will fill any arbitrarily shaped

polygon (which can be specified in either two or three dimensions) with a particular color or pattern. For example, you can use Polyfill to fill the box in the line plot above

with a red color: LDL> TvLCT, 255, 0, 0, 4 IDL> Erase, Color=l IDL> Polyfill, box-X-coords, box-y-coords, C010r=4, /Normal IDL> Plot, time, curve, Background=l, Color=2, /No~rase IDL> PlotS, box-X-coords, box-y-coords, Color=3, /Normal IDL> XYOutS, 0.5, 0.3, 'Critical Zone', Color=3, Size=2, $

Alignment = 0.5, /Normal

Color can sometimes serve to represent another dimensional property of a data set. For example, you might display XY data as a 2D plot of circles (polygons), with the color of each polygon representing some additional property of the data such as temperature or population density, etc. Let's see how this can be done.

IDL doesn't have a built-in circle-generator, but it is easy enough to write such a function. Open a text editor and type the code below to create the IDL function named Circle.

FUNCTION CIRCLE, xcent er, ycenter, radius points = (2 * !PI / 99.0) * FIndGen(100) X = xcenter + radius * Cos (points) y = ycenter + radius * Sin(points) RETURN, Transpose ( [ [X] , [y] 1 ) END

The X and Y points that comprise the circle will be returned in a 2 by 100 array. You can use this as input to the Polyfill command. Save the program as circle.pl-o mzd coinpile it by typing this command:

IDL> .Compile circle

Next, create some randomly-located X and Y data. (You will set the seed to begin, so that your results will look like the illustration in Figure 32, below.) Type:

IDL> seed = -3L IDL> X = RandomU(seed, 30) IDL> y = RandomU(seed, 30)

Let the Z values be a function of these X and Y values. Type:

Open a window and plot the XY locations, so you can see how the data is distributed in a random pattern. Type:

IDL> Window, XSize=400, YSize=350 IDL> Plot, X, y, Psym=4, Position=[0.15, 0.15, 0.75, 0.951, $

XTitle='X ~ocations', YTitle='Y Locations'

You are going to display the Z data associated with each XY point pair as a circle of a different color. To do this, you will need to load a color table and scale the Z data into the range of colors you have available to you. Type:

Usted puede fácilmente utilizar los comandos XYOutS y PlotS para crear leyendas para su pantallas gráficas.

Agregando Color a su Pantalla GráficoOtra útil manera para anotar su pantallas gráficas es a utilizar el comando Color. El Comando Polyfill es de bajo nivel gráfico para mostrar, el comando fill llena arbitrariamente cualquier forma de polígono (Que puede ser especificado en dos o tres dimensiones) con un color en particular o patrón. Por ejemplo, usted use Polyfill para llenar la caja en la parcela de línea anteriormente con un color rojo:

A veces el comando Color puede servir para representar otra propiedad dimensional para los datos establecido. Por ejemplo, usted muestre los datos XY como una gráfica en 2D de círculos (Polígonos), con el color de cada polígono que representa propiedades adicionales de los datos tal como temperatura o población, densidad,etcétera. Vamos a ver cómo esto puede ser hecho.

IDL no tiener incorporado un generador de círculos, pero es fácil y suficiente escribir una función.Abiendo un editor texto y tipear el código a continuación para crear en IDL la función llamado Circle.

Los puntos X e Y que comprender el círculo pueden ser retornados en una matriz de 2 por 100 elementos. Usted puede utilizar esto como entrada para el comando Polyfill. Guardar el programa

como circle.pro y compilarlo escribiendo este comando:

A continuación, crear aleatoriamente datos de posición X e Y. (Usted puede establecer la semilla(seed) a comenzar, de modo que su resultados buscados como la ilustración en Figura 32, a continuación.) Tipee esto:

Abiendo un ventana gradica y localizarla en XY, así usted puede ver cómo la datos estan

distribuidos al azar. Tipee esto:

Puedes mostrar los datos asociados a la variable Z para cada par de puntos XY con círculos

de colores diferentes. Para hacer esto, usted necesitará cargar una tabla de colores y escalar

los datos Z al alcance de colores usted pueda disponer. Tipee esto:

Los valores Z se crea con una función con estos valores X y Y. como esto:

Page 41: Coyote Traduction

Siitlple Graplzical Displays

IDL> LoadCT, 2 IDL> zcolors = BytScl(z, Top=!D.Table-Size-l)

The Circle progranl you are using in this example has a couple of weaknesses. Its major deficiency is that it doesn't always produce circles! If you specify the coordinates of the circle in the data coordinate system, the circle may show up on the display as an ellipse, depending upon the aspect ratio of the plot and other factors. (To obtain an excellent circle program, download the program TVCii-cle from the NASA Goddard Astrophysics IDL Library. You can find the library with a web browser at this World Wide Web address: http://idlastro.gsfc.i~asa.go~~fionzepage.ht~~zl.)

To avoid this deficiency in the Circle program, convert the data coordinates to device coordinates with the Coizvert-Coord command. Type:

IDL> coords = Convert-Coord(x, y, /Data, /To-~evice) IDL> X = coords(O,*) IDL> y = coords(l,*)

Now, you are finally ready to use the Polyfll command to draw the colored circles that represent the data Z values. Type:

IDL> For j=O, 29 DO Polyfill, Circle(x(j), y(j), 10), $ /Fill, Color=zcolors(j), /~evice

As an added touch, it would be nice to have a color bar that can tell you something about the Z values and what the color means. You can add a color bar to the plot with the Colorbar program that came with this book. Type:

IDL> Colorbar, position = [0.85, 0.15, 0.90, 0.951, $ Range= [Min (z) , Max (z) 1 , /vertical, $ Format=I(I5)l, Title='Z Values1

Your output should look similar to the illustration in Figure 32.

31 86

V) a, 3 - (d > 1595

N

5

0.0 0.2 0.4 0.6 0.8 1 .O X Locations

Figure 32: The color of the circles represents a tlzird dimensiorz irt tlzis 2Dplot. Figura 32: El color de los círculos representa una tercera dimensión en esta gráfica 2D.

El programa Circle usted esta usando en este ejemplo tiene debilidades. Su principal deficiencia es que no siempre produce círculos. Si usted especificalos datos de las coordenadas de los círculos del sistema, pueden mostrar en la pantalla como un elipse, dependiendo del aspecto de la proporción gráfica y otro factores. (Para obtener un excelente círculo, descargar la programa TVCircle de la NASA Goddard Astrofísica IDL Library. Usted puede encontrar la biblioteca con un navegador web en World Wide Web en la Dirección:http:/lidlastro.gsfc.nasa.gov/homepage.html.)

Para evitar este deficiencia en el programaa circle, convertir los datos coordenados a un recursode coordenadas con la con el comando Convert_CoordTipo:

Ahora, usted finalmente esta listo a utilizar lel comando Polyfill para dibujar círculos de colores que representan los valores de los datos Z. Tipee:

Como toque adicional, deberia tener una barra de colores que puede decidir los valores Z y su nivel de color. Usted puede añadir una barra de color a la gráfica con el comando Colorbar, programa que vino con este libro. Tipee:

Su salida debería ser similar a la ilustración en Figura 32.