NCL Home > Documentation > Manuals > Getting Started

GSUN > Examples > 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11


Example 1 - XY plots

This example creates five XY plots. The first four plots use data generated within the NCL script, and the fifth plot uses data read from an ASCII file.

The first plot has one curve, and the rest of the plots have multiple curves. Each plot has some aspect changed from the previous plot, like titles and line labels added, line colors and thicknesses changed, and markers added. More complex XY plots are shown in later examples. Please note that the words "line" and "curve" are used interchangeably in this example to refer to curves in an XY plot.

The semicolon ";" character allows comments in an NCL script. Comments must begin with a semicolon, and anything after the semicolon and before the next newline character is ignored by NCL. Comments may appear alone on a line or after an NCL command. Comments cannot appear on the same line before a command because everything after the comment character is ignored.

To run this example, you must download the following file:

gsun01n.ncl
and then type:
ncl gsun01n.ncl

Output from example 1

Frame 1 Frame 2 Frame 3 Frame 4 Frame 5

(Click on any frame to see it enlarged.)


NCL code for example 1

  1. load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl"  ; Load the NCL file that contains the gsn_* 
  2.                      ; functions used below.
  3. begin
  4.   x = new(9,float)  ; Define two 1D arrays of 9 elements each.
  5.   y = new(9,float)
  6. 
  7.   x = (/10.,20.,30.,40.,50.,60.,70.,80.,90./)
  8.   y = (/0.,0.71,1.,0.7,0.002,-0.71,-1.,-0.71,-0.003/)
  9. 
 10.   wks = gsn_open_wks("x11","gsun01n")  ; Open an X11 workstation.
 11. 
 12.   plot = gsn_xy(wks,x,y,False)         ; Draw an XY plot with 1 curve.
 13. 
 14. ;----------- Begin second plot -----------------------------------------
 15. 
 16.    y2 = (/(/0., 0.7, 1., 0.7, 0., -0.7, -1., -0.7, 0./),\
 17.          (/2., 2.7, 3., 2.7, 2.,  1.3,  1.,  1.3, 2./),\
 18.          (/4., 4.7, 5., 4.7, 4.,  3.3,  3.,  3.3, 4./)/)
 19. 
 20.   x@long_name  = "X"             ; Define attributes of x
 21.   y2@long_name = "Y"             ; and y2.
 22. 
 23.   plot = gsn_xy(wks,x,y2,False)  ; Draw an XY plot with 3 curves.
 24. 
 25. ;----------- Begin third plot -----------------------------------------
 26. 
 27.   resources                    = True          ; Indicate you want to
 28.                                                ; set some resources.
 29. 
 30.   resources@xyLineColors        = (/2,3,4/)    ; Define line colors.
 31.   resources@xyLineThicknesses   = (/1.,2.,5./) ; Define line thicknesses 
 32.                                                ; (1.0 is the default).
 33. 
 34.   plot = gsn_xy(wks,x,y2,resources)            ; Draw an XY plot.
 35. 
 36. ;---------- Begin fourth plot ------------------------------------------
 37.  
 38.   resources@tiMainString    = "X-Y plot"  ; Title for the XY plot
 39.   resources@tiXAxisString   = "X Axis"    ; Label for the X axis
 40.   resources@tiYAxisString   = "Y Axis"    ; Label for the Y axis
 41.   resources@tiMainFont      = "Helvetica" ; Font for title
 42.   resources@tiXAxisFont     = "Helvetica" ; Font for X axis label
 43.   resources@tiYAxisFont     = "Helvetica" ; Font for Y axis label
 44. 
 45.   resources@xyMarkLineModes = (/"Lines","Markers","MarkLines"/)
 46.   resources@xyMarkers       = (/0,1,3/)   ; (none, dot, asterisk)
 47.   resources@xyMarkerColor   = 3           ; Marker color
 48.   resources@xyMarkerSizeF   = 0.03        ; Marker size (default 
 49.                                           ; is 0.01)
 50. 
 51.   plot = gsn_xy(wks,x,y2,resources)       ; Draw an XY plot.
 52. 
 53. ;---------- Begin fifth plot ------------------------------------------
 54.  
 55.   filename = "$NCARG_ROOT/lib/ncarg/data/asc/xy.asc"
 56. 
 57.   data = asciiread(filename,(/129,4/),"float")
 58. 
 59.   uv      = new((/2,129/),float)
 60.   uv(0,:) = data(:,1)
 61.   uv(1,:) = data(:,2)
 62. 
 63.   lon     = data(:,0)
 64.   lon     = (lon-1) * 360./128.
 65. 
 66.   delete(resources) ; Start with new list of resources.
 67. 
 68.   resources                        = True
 69. 
 70.   resources@tiMainString           = "U/V components of wind"
 71.   resources@tiXAxisString          = "longitude"
 72.   resources@tiYAxisString          = "m/s"
 73.   resources@tiXAxisFontHeightF     = 0.02        ; Change the font size.
 74.   resources@tiYAxisFontHeightF     = 0.02
 75. 
 76.   resources@xyLineColors           = (/3,4/)     ; Set the line colors.
 77.   resources@xyLineThicknessF       = 2.0         ; Double the width.
 78. 
 79.   resources@xyLabelMode            = "Custom"    ; Label XY curves.
 80.   resources@xyExplicitLabels       = (/"U","V"/) ; Labels for curves
 81.   resources@xyLineLabelFontHeightF = 0.02        ; Font size and color
 82.   resources@xyLineLabelFontColor   = 2           ; for line labels
 83. 
 84.   plot = gsn_xy(wks,lon,uv,resources) ; Draw an XY plot with 2 curves.
 85. 
 86.   delete(plot)       ; Clean up.
 87.   delete(resources)
 88. end

Explanation of example 1

Line 1:

load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl"

Load the NCL script that contains the functions and procedures (the ones that start with "gsn_") that are used in this example. The load statement in NCL works much like include works in C and Fortran 90 programs.

Line 3:

begin

Start every NCL script with the begin statement and end it with the end statement.

Lines 4-5:

  x = new(9,float)
  y = new(9,float)
Declare two 1-dimensional float arrays of 9 elements each with the new statement. The first argument of new indicates the dimensionality of the variable, and the second argument its type. In this case, the two new statements are redundant, because in NCL you can declare variables by initializing them (as you do in the next two lines).

For an overview of NCL's variable types, see the "NCL data types overview" section of the NCL Reference Manual.

Lines 7-8:

  x = (/10.,20.,30.,40.,50.,60.,70.,80.,90./)
  y = (/0.,0.71,1.,0.7,0.002,-0.71,-1.,-0.71,-0.003/)
Assign values to the 1-dimensional arrays you just declared. In an assignment statement, a comma-separated list of array values is preceded by "(/" and terminated by "/)". Arrays in NCL are modeled after arrays in the C programming language; that is, they are row-major and begin at index 0 (instead of column-major and index 1 as in Fortran).

Line 10:

  wks = gsn_open_wks("x11","gsun01n")
To produce graphics with NCL, you need to tell it where to draw the graphics. The choices, which are also known as workstations, are an X11 window, an NCAR Graphics metafile (NCGM), or a PostScript file (regular, encapsulated, or encapsulated interchange).

The function gsn_open_wks opens one of these types of workstations so you can draw graphics to it. The first argument (a string) indicates where you want the graphical output drawn ("x11" for an X11 window, "ncgm" for an NCGM, and "ps", "eps", or "epsi" for a PostScript file). The second argument (also a string) determines the name of the file if you draw the graphical output to an NCGM or a PostScript file (name.ncgm for an NCGM file, and name.{ps,eps,epsi} for a PostScript file, where name is the second string you pass in). The second argument also comes into play when resource files are discussed in example 8 and 9.

The value returned from gsn_open_wks is a special variable of type graphic, which is an NCL variable type to define graphical objects.

Line 12:

  plot = gsn_xy(wks,x,y,False)
The function gsn_xy creates and draws an XY plot and returns the XY plot as a variable of type graphic (in most cases, you probably won't need to do anything with this return value). The first argument is the workstation you want to draw the XY plot to (the variable returned from the previous call to gsn_open_wks). The next two arguments are the variables containing the X and Y arrays that you want to plot. These two arguments can be of type float, double, or integer and can be 1-dimensional or multi-dimensional (explained below). The last argument is a logical value indicating whether you have set any "resources" for changing the look of a plot. To get the default XY plot that NCL provides, pass the value False for the last argument (in NCL, logical values are set with the special keywords True or False, which both must be capitalized).

The gsn_xy function draws the XY plot with tick marks selected at "nice" values. No title or X/Y axis labels are provided in the default plot, but these can be easily added as shown in the next few plots. You can also change the style of the tick marks as shown in example 7.

By default, when a plot is drawn to an X11 window or an NCGM file, it has a black background and a white foreground. If a plot is drawn to a PostScript file, it has a white background and a black foreground. In later examples, you will learn how to specify the background and foreground colors, and when you do this, the plot has the same colors, no matter which workstation you draw it to.

Since you opened a workstation type of "x11", the gsn_xy function produces an X11 window on which you need to click with the left mouse button to advance to the next frame.

Line 14:

;----------- Begin second plot -----------------------------------------
Divider in the code to indicate the start of the code for the second plot.

Draw an XY plot with three curves, each curve having nine points.

Lines 16-18:

  y2 = (/(/0., 0.7, 1., 0.7, 0., -0.7, -1., -0.7, 0./),\
         (/2., 2.7, 3., 2.7, 2.,  1.3,  1.,  1.3, 2./),\
         (/4., 4.7, 5., 4.7, 4.,  3.3,  3.,  3.3, 4./)/)
Define a 3 x 9 array (the first dimension represents the number of curves, and the second dimension represents the number of points). Note that this time you are not using new to declare the array, because in NCL you can create variables by assigning values to them. NCL is able to determine the dimensionality and type of a variable by the way it is initialized.

For example, to create a 2 x 3 x 4 integer array called i with each value set to 0, use the following NCL statement:

  i = (/ (/ (/0,0,0,0/), (/0,0,0,0/), (/0,0,0,0/) /),\
         (/ (/0,0,0,0/), (/0,0,0,0/), (/0,0,0,0/) /) /)
The above could have also been accomplished with the following two lines:
  i = new((/2,3,4/),integer)
  i = 0
The "\" character is used in NCL as a line continuation character.

Lines 20-21:

  x@long_name  = "X"
  y2@long_name = "Y"
NCL variables are more general than variables used in traditional programming languages such as C and Fortran. As usual, they contain values, but they may also contain ancillary information about the variable. This additional information is often called "metadata." Metadata is divided into three categories: attributes, named dimensions, and coordinate variables.

Variables can have an unlimited number of attributes assigned to them, and each attribute is assigned to a variable using the "@" symbol.

In lines 20-21, you are creating an attribute called "long_name" for both the x and y2 variables. For more information on variable properties in NCL, see the "Variables" section in the "Basics."

By default, if an attribute called "long_name" is set for either the X or Y data arrays, (as is commonly done in netCDF files), then gsn_xy uses this attribute to label the X and/or Y axis in the XY plot (unless you have overridden this by setting resources as shown below).

Line 23:

  plot = gsn_xy(wks,x,y2,False)
Draw a new XY plot, using the same X array from the first plot and the new y2 array you just defined. Since x is only a 1-dimensional array, NCL pairs the values in the x array with the values in each of the three curves in the y2 array. If a 3 x 9 X array had been declared in addition to the 3 x 9 Y array, then each value in the Y array would have been paired with the corresponding value in the X array.

Note that if more than one curve is drawn in an XY plot, then gsn_xy draws each curve with a unique dash pattern. There are 16 different dash patterns available; see the list of "dash patterns" in the graphics documentation.

Note the new X and Y axis labels that result from the attribute "long_name" being set for each axis.

Line 25:

;----------- Begin third plot -----------------------------------------
Draw the same three curves, using different colors and line thicknesses for each one.

Line 27:

  resources                     = True
This line introduces the concept of using "resources" to change the look of a plot. In NCL, there are hundreds of resources you can set for changing line colors and thicknesses, adding titles, changing fonts, creating label bars and legends, changing map projections, modifying the size of a plot, masking out certain areas, etc. There are also resources for changing the data of a plot, like setting minimum and maximum values, selecting strides or subsets of data, and setting missing values.

Most resources have default values that are either hard-coded or set dynamically by NCL when you run the NCL script. For example, the line thickness for a curve is hard-coded to a value of 1.0, but the minimum and maximum values of a curve are set dynamically according to the actual minimum and maximum data values used in the XY plot. You only need to set a resource if you want to change its default value.

Resources are grouped by the type of graphical object or data they describe, and these groupings are discussed here and in other examples.

To set resources for use by the gsn_* suite of functions, first define a variable of type logical and set its value to True, then specify the resources as attributes of this logical variable. As stated above, a variable can have an unlimited number of attributes. This variable that you create should then get passed to the appropriate gsn_* plotting routine for the resources to take effect.

Important note: This method for setting resources is specific to the gsn_* suite of functions and procedures. Setting resources using straight NCL code is quite different, and is covered in the "Going beyond the basics" section of this document.

Line 30:

  resources@xyLineColors        = (/2,3,4/)
Set the resource xyLineColors to define a different line color for each line. The default is 1 which is the foreground color ("white" in this case). The colors specified here are represented by integer index values, where each index maps to a color in a predefined color table (also called a "color map"). Since a color table has not been defined in this example, a default color table with 32 indices is provided by NCL (later examples will show how to create your own color map). To see the default color table, go to the "Color tables" section of the NCAR Graphics Reference Manual. In the default color table, the integer values 2, 3, and 4 represent the colors "red", "green", and "blue" respectively.

Color resources can also be set using named colors, so the xyLineColors resource could have been set with the following code:

  resources@xyLineColors        = (/"red","green","blue"/)
Named colors are covered in more detail in examples 4 and 7.

If you had wanted the same line color for each curve, but wanted it something other than "1", then you could have used the singular resource, xyLineColor.

XY plot resources belong to the "XyPlot" group and start with the letters "xy". Each XyPlot resource is documented with its type and its default value in the XyPlot resource descriptions.

Line 31:

  resources@xyLineThicknesses   = (/1.,2.,5./)
Using the xyLineThicknesses resource, define a different line thickness for each curve. The default thickness is 1.0, so a value of 2.0 doubles the line thickness and a value of 5.0 increases the line thickness by a factor of 5, and so on. Again, you could have used the singular resource xyLineThicknessF to set all the curves to the same thickness.

Line 34:

  plot = gsn_xy(wks,x,y2,resources)
Draw the plot, this time passing the list of resources that you just created. Each curve is a different color and has a different line thickness.

Line 36:

;---------- Begin fourth plot ------------------------------------------
Create the same plot as before, only add a title at the top, change the X and Y axis labels, change the font of the title and labels, and use markers and/or lines to draw each curve.

Since you are creating the same plot as before, you want to keep the same resources that you set for the previous XY plot. You can just add more attributes to the resources variable to customize the plot some more.

If you had wanted to go back to all the default resources before creating the next XY plot, you could have either used a new variable name for the resources, or deleted the current list of resources with the delete(resources) command and started over with a new list.

Lines 38-40:

  resources@tiMainString    = "X-Y plot"
  resources@tiXAxisString   = "X Axis"
  resources@tiYAxisString   = "Y Axis"
Set some resources for adding a title to the top of the plot and for changing the labels of the X and Y axes. Title resources belong to the "Title" group and start with "ti.

Lines 41-43:

  resources@tiMainFont      = "Helvetica"
  resources@tiXAxisFont     = "Helvetica"
  resources@tiYAxisFont     = "Helvetica"
Set some resources for changing the font of the titles you just defined above. Fonts can be set by using a string that describes the font, or by using an index into a font table. A table of all the available fonts along with their names and index values appears in the "Font table" section of the NCAR Graphics Reference Manual.

Note that predefined strings, like those listed in the font table, are case-insensitive, and that you could have specified the font with "helvetica" or "HELVETICA" or any another combination of uppercase and lowercase characters.

Lines 45-46:

  resources@xyMarkLineModes = (/"Lines","Markers","MarkLines"/)
  resources@xyMarkers       = (/0,1,3/)
Use the xyMarkLineModes resource to add markers to the curves (since the default is to draw all curves without markers). There are three types of lines that can be drawn: regular lines ("Lines"), markers only ("Markers"), and lines with markers ("MarkLines"). In this plot, you are using this resource to invoke all three kinds of lines. The xyMarkers resource defines the type of markers you want to use. There are seventeen marker styles to choose from.

Lines 47-48:

  resources@xyMarkerColor   = 3
  resources@xyMarkerSizeF   = 0.03
By using the "singular" resources xyMarkerColor and xyMarkerSizeF instead of the "plural" resources xyMarkerColors and xyMarkerSizes, you get the same marker color and size for all the lines that have markers. The default marker size is 0.01, so a value of 0.03 triples the marker size.

Line 51:

  plot = gsn_xy(wks,x,y2,resources)
Draw the plot with the new resources you set.

Line 53:

;---------- Begin fifth plot ------------------------------------------
Read in some data from an ASCII file, set several resources for titles, line colors, and labeling lines, and then create an XY plot with two curves.

Lines 55-57:

  filename = "$NCARG_ROOT/lib/ncarg/data/asc/xy.asc"

  data = asciiread(filename,(/129,4/),"float")
Read in an ASCII file using the NCL function asciiread. NCARG_ROOT is an environment variable (that must be set to run these NCL scripts) and you can use environment variables in NCL in a file path name by prefixing a "$" to the name.

The first argument of asciiread is the file name, the second argument (a 1-dimensional integer array) is the dimensionality of the data you are reading in, and the third argument (a string) is the type of the data. In this case, the ASCII data file has 4 columns of data with 129 rows each, so a dimensionality of (/129,4/) is used to read in the data.

Lines 59-61:

  uv      = new((/2,129/),float)
  uv(0,:) = data(:,1)
  uv(1,:) = data(:,2)
Create a 2-dimensional float array dimensioned 2 x 129 and assign some values of data to it. The notation "(:,1)" indicates the second set of 129 values from data (remember, arrays in NCL start at index 0, not index 1). If you had wanted to select elements 50 to 100 of the first set of 129 values, you would have used the notation "(49:99,0)".

Lines 63-64:

  lon     = data(:,0)
  lon     = (lon-1) * 360./128.
Assign data's first set of 129 values to the variable lon. Since the values stored in the lon variable range from 1.0 to 129.0, and are actually supposed to represent longitude values from 0.0 to 360.0 in steps of 360/128, you need to convert each value by subtracting 1 and multiplying it by 360/128. In NCL, you can do scalar arithmetic on a whole array using the same notation as if it were a scalar value. You can also multiply, divide, add, and subtract arrays in one step as long as they are the appropriate size for doing such array computations.

Lines 63-64 could also have been combined into one line:

  lon     = (data(:,0)-1) * 360./128.
Lines 66-68:

  delete(resources)

  resources                        = True
Assuming you don't want to use any of the resources that had been set for the earlier plots, you can start with a new template of resources using the delete command. If you plan to set some new resources, the variable resources must be again set to True, since delete removes all information relating to it. You could have also just used a new variable name.

Lines 70-74:

  resources@tiMainString           = "U/V components of wind"
  resources@tiXAxisString          = "longitude"
  resources@tiYAxisString          = "m/s"
  resources@tiXAxisFontHeightF     = 0.02
  resources@tiYAxisFontHeightF     = 0.02
Set some resources for putting a title on the plot, labeling the X and Y axes, and changing the font size of the X/Y axis labels.

Lines 76-82:

  resources@xyLineColors           = (/3,4/)
  resources@xyLineThicknessF       = 2.0
  resources@xyLabelMode            = "Custom"
  resources@xyExplicitLabels       = (/"U","V"/)
  resources@xyLineLabelFontHeightF = 0.02
  resources@xyLineLabelFontColor   = 2
Set some resources for defining line colors and thicknesses and for creating line labels. You set xyLabelMode to "Custom" to indicate that you want to customize how to label the XY plot curves (there are no labels by default). You can indicate what labels you want with the xyExplicitLabels resource. The xyLineLabel* resources used here change the font size and color of the line labels.

Line 84:

  plot = gsn_xy(wks,lon,uv,resources)
Draw an XY plot, using the new list of resources you just set.

Lines 86-87:

  delete(plot)
  delete(resources)
Use the delete command to remove some of the variables created in this NCL script. This is not really necessary in this case, since you are at the end of the NCL script, but it's a good idea to get in the habit of cleaning up variables that you no longer need.

Line 88:

end
End every NCL script with end.