Creating Graphical Output
NCL uses the NCAR Graphics High Level Utilities Library (HLU) to produce its
graphical output. Complete documentation on the HLUs is available from the
HLU User Guide and the HLU Reference Guide. In addition, NCL source code
examples using the HLU library can be obtained from the
Quick Start Guide Examples
This section of the NCL reference guide covers some basics of
using the HLU libraries and NCL's interface to the HLUs. This is not an
exhaustive manual for the HLUs. This section is intended to be a basic
overview of useful features.
Plot creation can get very complex depending on how you want to look at your
data. NCL's interface for creating graphics is called the High Level Utilities (HLUs). There are five basic steps needed to create a simple plot.
Issues such as combining plots, multiple plot frames, adding maps, and annotations are covered later.
- Open a workstation
This is probably the simplest decision to make. X11 output will
create an X11 window on the display specified by the DISPLAY environment
variable. NCGM is a compact, efficient, and portable vector description of
the graphical output. NCGM can be translated and viewed using the application
ctrans and animated using the idt application. NCGM is recommended for
the efficient storing of NCAR Graphics-generated output. PostScript can be
output directly. The PostScript generated by the HLUs is encapsulated so
it can be directly imported into documents or PostScript-compatible software
and hardware devices. The workstation is responsible for managing all the
colors used by plots. Each workstation has "wkColorMap" resources that
can be set to a nx3 array of red, green, and blue colors. In addition,
several default color maps can be set by using their names instead of an
array of color combinations.
The following are the Class names needed to create
each of the output types using the create statement:
- xWorkstationClass - X11 output
- ncgmWorkstationClass - NCGM output
- psWorkstationClass - PostScript output
- Describe your data
There are HLU objects whose primary purposes are to describe the
data in a flexible fashion. The HLU plot object needs to know what the dimensionality of the data is, what the coordinates of the data are, whether the data
contains missing values, and finally what data type the data is. If it weren't
for these data objects, you'd have to convert your data into a common form before
visualizing it. The data objects provide the flexibility to represent your data
in the fashion it is represented. There are three basic types of data objects.
There is the scalarFieldClass that describes scalar fields which are used
by the contourPlotClass. There is the coordArraysClass which is used by
the xyPlotClass, and finally there is the vectorFieldClass which is used by
the vectorPlotClass and the streamlinePlotClass. A data object must be
defined before the next step.
- Create a plot object and add your data
Producing plots using the HLUs is a different a paradigm than most
people are used to. In NCL, you create an instance of a plot which can then
be drawn and/or manipulated, rather than setting up a single graphics state
or calling a single procedural interface with a lot of parameters. HLU plots
exist and can be drawn independently from each other. This provides a
great deal of flexibility, but can be a little confusing
for beginners. Just as you create workstations and data objects, you can
create plot objects. There are many types of plots which are listed
in the HLU reference manual
- Draw the plot
The draw procedure is
called to draw a plot. Once a plot is created, draw can be called at any
time, a feature unique to NCL.
- Call the frame command
Once a plot has been drawn to an output frame and no other plots
are going to be drawn on the same frame, a call to the frame procedure is needed. This call, when using
either Postscript or CGM workstations, causes a new page to be inserted into
the output file. If X11 output is being used, a frame call will wait for
a button click (unless "wkPause" is set to False) and then clear the screen.
The following is a short script demonstrating these steps. The available
plot types are listed in the HLU reference manual. The following creates a simple filled contour plot from a
data file included with the NCAR Graphics release. The following script
should run without modification on your system if the NCAR Graphics data
directory was installed.
; Step 1)
; Open an X11 output window
xwks = create "xwks" xWorkstationClass defaultapp
"wkColorMap" : "temp1"
; Step 2)
; Open the data file and describe the data
data_file = addfile(ncargpath("data") + "/cdf/Pstorm.cdf","r")
; Describe data by creating a scalarField object
data = create "data" scalarFieldClass defaultapp
; Select the first time step
"sfDataArray" : data_file->p(0,:,:)
"sfMissingValueV" : data_file->p@_FillValue
"sfXArray" : data_file->p&lon
"sfYArray" : data_file->p&lat
; Step 3)
; Create a contourPlot with the above data
contour = create "contour" contourPlotClass xwks
"cnScalarFieldData" : data
"cnFillOn" : True
; Step 4)
; Call draw
; Step 4)
; Call frame
The resources vpXF, vpYF, vpWidthF,i and
used to specify the size of the output plot. The values of these resources can
be set to values between 0.0 and 1.0. The output frame, regardless of which
output device is open, has coordinates called Normalized Device Coordinates (NDC).
These coordinates range from 0.0 to 1.0 along each axis of the output frame.
The setvalues statement is used to assign values to each of these
resources. Every object that can be drawn accepts these four resources
for setting size.
The transformation is defined as how the data coordinates are mapped
to the screen. Contour plots, vector plots, and streamline plots all work
the same way, xy plots are slightly different.
Conceptually you must think of two transformations. One is the natural
transformation of the data which is defined by the data's coordinates.
The second is the view transformation (how you want to look at the data).
If the data's coordinates are evenly spaced, then the data's natural
transformation is a Linear uniformly spaced transformation. In order to
view the data in a different transformation you must create an additional
plot, either a mapPlot, an irregularPlot, or a logLinearPlot and call the
overlay procedure. This will allow you
to select how the data are displayed.
A note about IrregularPlots. These are NOT randomly spaced plots, they
are plots where the
coordinates for each axis are not evenly spaced, but are still rectilinear, meaning all
adjacent points along the X axis have the same Y coordinate and vice versa. This type of
data's natural transformation is irregular; when the data is viewed, it is neither
a linear projection nor a log projection. The tick marks will be irregularly spaced.
So to sum it up for contour plots and similar plots, if no coordinate values are set for the plot's scalar field,
the transformation will be integer grid coordinates which represent the integer indexes of each grid point. If coordinates are set using the sfYCStartV,
sfYCEndV, sfXCStartV, and sfXCEndV,
then the HLUs assume that the grid points
are equally spaced starting at the beginning and end of each coordinate range.
In this case the default view will be use linear axis to display the contour.
The resources sfYArray and
sfXArray are used if
the grid points are not equally spaced (this happens with the latitude coordinate for Gaussian grids). In this situation the output display is not a linear
axis, it is called an irregular axis. This transformation essentially displays
the grid with each point being equally spaced but marks the axis by the
function defined by the sequence of points in the coordinate arrays. This
type of transformation is especially useful for coordinate systems which are
neither log base 10 nor linear. Example cn03 demonstrates this type of transformation.
Since the HLUs are object oriented, it is very simple to change the data
for a plot. Changing the data does not require recreating plots.
The setvalues statement is used to reset the data array in the
plot's data object. For example, consider changing the above plot from using
the first time step to using the second. The following is all that is
needed to update the plot and redraw it:
"sfDataArray" : data_file->p(1,:,:)
That's it. No need to do anything more. The contour plot is automatically
informed that the data have changed, and it updates itself.
In XyPlot, it is possible to have multiple curves and data objects
in a single plot. Because of this, a special function to add new data and
a special procedure to remove old data can be used without affecting the data already in the plot. These routines
are NhlAddData and NhlRemoveData. The return
value from NhlAddData is called a Data Specific Object. It is used
to allow individual customization of how a piece of data is displayed. For
instance, it is used in the XyPlot to send line styles, labeling, and
colors for each data object; see the XyPlot
section on modifying a plot.
The setvalues statement
can be used to modify a plot once it has been created. Modifications could
be anything from resizing, to changing the data, to changing the colors.
The following are frequently used resources for configuring the ContourPlot object. For a full list of these resources and more
descriptions, see the HLU reference guide section for
The following are frequently used resources for configuring the XyPlot object. For a full list of these resources and more
descriptions, see the HLU reference guide section for
XyPlot. The most
important thing to know about the XyPlot that makes it different from other plots is that it accepts multiple data objects. The
data objects can be added and removed at will. Each data object can represent one or more curves. Since these can be added and
deleted, it is difficult to specify colors and curve-specific attributes, like line styles and labels, in the XyPlot itself. Because
of this the XyPlot uses a special data specific object for configuring colors and line styles
that is associated with each of the
XyPlot's data objects. In this way it is not confusing as to which color belongs to which piece of data.
- "cnScalarFieldData": This resource must be set to create
a contour plot. It accepts a single reference to a ScalarField object. The scalar field describes the data,
their coordinates, and missing values to the contour object.
- "cnLevelSelectionMode": This resource determines how the contour intervals will be chosen. There are four options: The default is "AutomaticLevels" which
means each time the "cnScalarField" resource is set, the contour plot will
choose "nice" values for the contour intervals. "ManualLevels" allows you to set the
minimum, maximum, and spacing for the intervals through the resources "cnMaxLevelValF", "cnMinLevelValF", and "cnLevelSpacingF". If these are set, then the contour plot will not reset itself when new data are set. "ExplicitLevels" allows you to set each interval to a specific value using the "cnLevels" resource. Finally, the
option "EqualSpacedLevels" simply divides up the range of data into equally spaced levels.
- "cnFillOn": Causes the contour plot to draw filled contours when set to "True". The colors for the filled contours are determined by
When set to "True" causes the contour plot to fill each grid point with a
color rather than interpolate contour areas. This is very useful if the data
being viewed are categorical data, meaning they do not represent a function.
Examples of this type of data could be vegetation types, demographic data, etc. This mode is also much faster for large grids.
- "cnLinesOn": Turns the contour lines on and off.
- "cnLineLabelsOn": Turns the contour line labels on and off. Sometimes drawing the contour line labels can be expensive, so turning them off can improve performance.
XyPlot accepts instances of the CoordArrays object. These can be set
either using setvalues, create, or by using
NhlAddData to add individual pieces of data to the plot.
- "xyCoordDataSpec": Used to retrieve the
XyPlot's data-specific objects at any time. You can use getvalues and this resource to retrieve all of the XyPlot's current
data specific objects.
- "xyXStyle" and "xyYStyle": These resources control how each axis
of the xyPlot is viewed. The valid options are: LOG, LINEAR, and IRREGULAR.
If IRREGULAR is used, then
"xyXIrregularPoints" or "xyYIrregularPoints" must be specified. The default is LINEAR.
The following are resources that apply to the XyPlot data specific object, objects referenced by the resource "xyCoordDataSpec":
The following are frequently used resources for configuring the VectorPlot object. For a full list of these resources and more
descriptions, see the HLU reference guide section for
VectorPlot can display vectors in a variety of fashions. There are line vectors, filled vectors, and wind barbs. A variety of
"looks" can be obtained by adjusting arrow head and tail sizes as well as shape.
- "xyLineColors": Sets the line colors for each curve represented by the corresponding CoordArrays object.
- "xyDashPatterns": Sets the dash patterns for each curve represented by the corresponding CoordArrays object. The values 1-16 are valid patterns.
- "xyMarkLineModes": Sets whether markers, lines, or both should
be used when drawing the curves represented by the corresponding CoordArrays object. The options are "Lines", "Markers", or "MarkLines".
- "xyMarkers": If xyMarkLineModes is set to "Markers", then this resource is used to select which marker will be drawn for each curve. A list of markers appears on the
- "xyLabelModes": Lines can be labeled with either custom labels or letters. This resource determines how each line is drawn. The valid options are "noLabels", "lettered",
and "custom". If "custom" is selected, then the resource
"xyExplicitLabels" is used to provide the strings for the custom labels.
- "xyLineThicknesses": Changes the thickness of each curve represented by the corresponding CoordArrays object.
The following are frequently used resources for configuring the StreamLinePlot object. For a full list of these resources and more
descriptions, see the HLU reference guide section for
Legends, Label Bars, TickMarks, and Titles are special types of annotations that
are controlled by an object called a
VectorPlot, StreamLinePlot, XyPlot, and MapPlot are
all PlotManagers. This means that they can accept overlayed plots, they accept
and finally that they manage Legends, Label Bars, TickMarks, and Titles.
When a PlotManager is "managing" one of these types of annotations,
it means the user does not have to create and configure these objects. For
example, when ContourPlot displays a LabelBar, it configures each of the
LabelBar's filled boxes and sets the valid label resources. If users were
to create a LabelBar manually, they'd have to set all the applicable LabelBar
resources, including its position. The PlotManager takes care of these details.
Also when an annotation like LabelBar is managed by a PlotManager, the LabelBar's
resources can be directly set through the managing object (ContourPlot, XyPlot...) rather than through the LabelBar object itself.
- "vcVectorFieldData": This resource is used to assign an instance of a
VectorField object to the VectorPlot.
- "vcScalarFieldData": Optionally, vectors can be colored
by an additional scalar value. This resource is used to assign the ScalarField. To display the plot using these data, you must set "vcUseScalarArray" to True.
- "vcGlyphStyle": Selects the style of vector. "LineArrow",
"FillArrow", and "WindBarb" are the options.
- "vcRefMagnitudeF" and "vcRefLengthF": These resources are key resources for setting the sizes of output vectors when using "LineArrow" and "FillArrow" glyph styles. "vcRefMagnitudeF" is
a data value that represents what is considered a reference vector. If not
set, the maximum vector magnitude is used as the reference vector. The resource "vcRefLengthF" sets the size vector for this reference value. All other vectors are scaled relative to the value of "vcRefMagnitudeF". So if "vcRefMagnitudeF" is the maximum magnitude, all vectors will be smaller. If "vcRefMagnitudeF" is a mid-range value, then some vectors will be bigger and some smaller. If "WindBarb" glyphs are used, then "vcRefLengthF" sets the
length of all the windbarbs.
This resource can be used to assure that vectors have a visible minimum size. Sometimes vectors become too small to see, especially if the magnitudes
vary greatly, this resource establishes a minimum size.
This resource is used when the "vcScalarFieldData" resource is set. It specifies how the levels for the input scalar field should be determined and colored.
This resource works just like ContourPlot's "cnLevelSelectionMode".
The following resources are PlotManager resources that control the display of Legends, LabelBars, TickMarks, and Titles:
- "pmLabelBarDisplayMode": Turns on and off the plot's LabelBar. Valid options are "NoCreate", "Never", "Always", and "Conditional". "Always" and "Never" are
self explanatory. "NoCreate" can be used when creating a new plot to prevent
the creation of a LabelBar. Otherwise a LabelBar object is created but just not
drawn unless "Always" is set. "Conditional" leaves the display of the LabelBar up to the PlotManager and depends on the plots overlayed on each other.
- "pmTickMarkDisplayMode": Options are the same as pmLabelBarDisplayMode.
- "pmTitleDisplayMode": Options are the same as pmLabelBarDisplayMode.
- "pmLegendDisplayMode": Options are the same as pmLabelBarDisplayMode.
- "pmLabelBarSide": Sets which side of the plot the LabelBar will appear. Make sure to set "lbOrientation".
- "pmLegendSide": Sets which side of the plot the Legend will appear. Make sure to set "lgOrientation".
For specific resources, see the HLU reference guide sections for the
MapPlots are a special type of plot. Although instances of MapPlot don't accept
data, they do provide a transformation from lat/lon coordinates to screen coordinates. Furthermore, one or more of the other types
of plots can be overlayed using the overlay procedure. One important item to
note is that MapPlot
is really two objects: the MapPlot and the
The only reason to be aware of this is that some MapPlot resources -- those
that configure map outlines and colors -- are documented in the MapPlot
reference page, and others -- those that configure the transformation --
are documented in the MapTransformation section of the reference guide.
Both sets of resources are set through a single MapPlot instance.
The following are important resources for configuring MapPlot:
Resource files are external text files that can be used to create default
templates for resources. There are two user-editable
default resource files. One can be put in your home directory and is named ".hluresfile", the other is named "ncl.res" and goes in the
directory you're running NCL. Different directories can have different
"ncl.res" files, which means different directories can have
different default plot configurations. There are other more advanced uses
of resource files which are not covered here. See the
HLU user guide section on
Understanding resources and the section on
Using resource files. The file ".hluresfile" is used to supply resources globally, meaning
every time you run NCL the defaults set in ".hluresfile" can be used. If the "ncl.res" file exists in NCL's current working
directory, then the resources in "ncl.res" can be used. It is important to note that resources in an "ncl.res" file will override
those in ".hluresfile".
Chooses between the low-resolution and high-resolution map outline datasets.
To use low resolution, the default, set this resource to "Ncarg4_0", and
to use the high-resolution map outline set, set this resource to "Ncarg4_1".
Using the high-resolution set on "MAXIMALAREA" plots is not
recommended as this map outline set is very large, and the resolution of
most displays is not enough to be of any benefit. For non-"MAXIMALAREA"
plots, the high-resolution set provides exceptional resolution.
Sets the map projection.
Establishes the latitude that will be at the center of the projection plane.
This resource is not valid with the LambertConformal projection.
Establishes the longitude that will be at the center of the projection plane.
This is the resource to use to create a MapPlot which is not a maximal
projection (i.e. zoom in on a portion). There are many options for this
resource, more than can be explained here. The options include:
- "MaximalArea" - The default, causes entire projection to be rendered.
- "LatLon" - Limits the projection to a minimum and maximum latitude and longitude. Probably the most straightforward,
although some odd aspect ratio plots are possible when using non-rectangular
projections. Works great with the "CYLINDRICALEQUIDISTANT" and "MERCATOR"
projections. This option uses the resources
to set the map limits.
- "NPC" - Stands for "Normalized Projection Coordinates". This is most useful when using NCL interactively. However, NPC
values can be set when creating a map plot. The area defined by the viewport
(vpXF, vpYF, vpWidthF, and vpHeightF) is
referenced as values from 0.0-1.0 for each axis starting at the lower left
corner. So if you want to zoom in on a specific section of the "MaximalArea"
projection, for example say the upper right corner of a plot, you can set
to .5 , 1.0, 1.0, .5 respectively.
- "NDC" - Stands for "Normalized Device Coordinates" or screen coordinates. This option allows you to set screen coordinates as the reference points for setting the map limits. NDC units run from 0.0 to 1.0 from the lower left corner of the output frame. Use the resources
to set these normalized device coordinate limits.
- "Corners" - This limit mode is suggested for non-rectangular projections. It allows you to set the corners, in lat/lon
coordinates, that you want to be the corners of the new projection.
- "Points" - Points is the analog of "Corners" using NDC units.
- "Angles" - Mainly useful with the Satellite projection.
- "mpFillOn": Turns map filling on and off.
- "mpOutlineBoundarySets": Determines which outline set is
used. The options are: "NoBoundaries", "Geophysical", "National", "USStates", "GeophysicalAndUSStates", and "AllBoundaries".
- "mpPerimOn": Turns on a line that is drawn around the perimeter of the map.
- "mpGridAndLimbOn": Turns on the grid.
- "mpGridLatSpacingF": Sets the spacing in degrees for the latitude grid.
- "mpGridLonSpacingF": Sets the spacing in degrees for the longitude grid.
Every time you create a plot, a name must be given to that plot. This
name can be used to determine which resources should be
applied to the plot being created. By using the name of the plot,
specific resources can be directed to specific plots. For example,
consider the following small resource file. This example shows how to
set defaults for two different projections.
By using this resource file, the NCL script is greatly shortened. To get
an idea of how resource files work, run the following example on your own.
Save the resources in a file called "ncl.res", and run the script in the
This should be enough to convince you of the utility of resource files and
of the convenience that carefully designed resource files can provide.
x = create "x" xWorkstationClass defaultapp end create
mp0 = create "Pacific Ocean" mapPlotClass x
"vpXF" : .01
"vpYF" : .99
"vpWidthF" : .9
"vpHeightF" : .5
mp1 = create "Atlantic Ocean" mapPlotClass x
"vpXF" : .01
"vpYF" : .49
"vpWidthF" : .9
"vpHeightF" : .5
*Pacific Ocean*mpCenterLatF : 0.0
*Pacific Ocean*mpCenterLonF : 180.0
*Pacific Ocean*mpProjection : CYLINDRICALEQUIDISTANT
*Pacific Ocean*mpLimitMode : LATLON
*Pacific Ocean*mpMaxLatF : 67.67
*Pacific Ocean*mpMinLatF : -34.0
*Pacific Ocean*mpMaxLonF : 291.00
*Pacific Ocean*mpMinLonF : 100.00
*Pacific Ocean*vpYF : .92
*Pacific Ocean*mpFillOn : True
*Pacific Ocean*mpMonoFillColor : True
*Pacific Ocean*mpMonoFillPattern : False
*Pacific Ocean*mpMonoFillScale : False
*Pacific Ocean*mpOceanFillPattern : -1
*Pacific Ocean*mpLandFillPattern : 17
*Pacific Ocean*mpLandFillScaleF : .70
*Atlantic Ocean*mpCenterLatF : 0.0
*Atlantic Ocean*mpCenterLonF : 0.0
*Atlantic Ocean*mpProjection : CYLINDRICALEQUIDISTANT
*Atlantic Ocean*mpLimitMode : LATLON
*Atlantic Ocean*mpMaxLatF : 67.67
*Atlantic Ocean*mpMinLatF : -34.0
*Atlantic Ocean*mpMaxLonF : 17.
*Atlantic Ocean*mpMinLonF : -98.0
*Atlantic Ocean*vpYF : .92
*Atlantic Ocean*mpFillOn : True
*Atlantic Ocean*mpMonoFillColor : True
*Atlantic Ocean*mpMonoFillPattern : False
*Atlantic Ocean*mpMonoFillScale : False
*Atlantic Ocean*mpOceanFillPattern : -1
*Atlantic Ocean*mpLandFillPattern : 17
*Atlantic Ocean*mpLandFillScaleF : .70
Annotations are an advanced topic. Essentially Annotations are ancillary plots that can be "attached" to plot that is a PlotManager.
This means that the ancillary plot can be redrawn, moved, and even resized by drawing or changing the position of the PlotManager
to which it is assigned. These ancillary plots can be TextItems, LabelBars, Legends, TickMarks, or other Plots. For each plot
added to a PlotManager as an annotation, an object called an AnnoManager is
created. This additional object contains resources for positioning the annotation. The following are key AnnoManager resources:
Since lines and polygons need to have colors, dash patterns, and fill
patterns associated with them, a special object is needed to specify these
options. This object is called a GraphicStyle object. The GraphicStyle object
can be modified just like other objects using setvalues. A custom GraphicStyle object can be created using the create command, or
the default one can be retrieved from the current workstation using the resource
"wkDefGraphicStyleId". The graphic style has resources for changing line styles, colors, polygon fill patterns,
markers, and line labels. Also needed to draw lines and primitives is either a plot on which the line or polygon will be drawn,
or a workstation on which the line or polygon will be drawn. If a plot is
provided, then the polygon or line is clipped to the
viewport of the plot. If a workstation is provided, then the polygon or
line is clipped to the workstation frame.
- "amZone": This specifies an ordering that is used to draw annotations. However, this ordering is spatial rather than sequential. Annotations are drawn from lower number zones out to larger number
zones. If two objects occupy zones 2 and 3 respectively, then the plot in zone 3 will be drawn after the plot in zone 2, and it will
be drawn such that the two objects don't overlap. The concept is basically that objects in different zones are guaranteed not to
overlap. For more information on how zones work, please read the
PlotManager Location Control Model in the HLU reference manual.
- "amSide": In addition to the above zone concept, a side to place
the annotation on can be specified. The options are "TOP", "BOTTOM", "LEFT",
- "amOn": When
True, the annotation will be drawn every time the main plot is drawn. When
False, the annotation is not drawn.
- "amTrackData": When True, the annotation will "track" a specific data location. This is useful for positioning a piece of text over a specific data location. This resource must be used with "amDataXF" and "amDataYF".
There are six procedures that use the GraphicStyle object; three use data
coordinates for points, and three use NDC or screen coordinates. Each takes
a plot or workstation, a graphic style, and two vectors of coordinates
either in NDC units or data coordinates. They are:
- NhlDataPolygon - draws a polygon clipped to a plot's viewport in data coordinates
- NhlDataPolyline - draws a line clipped to a plot's viewport in data coordinates
- NhlDataPolymarker - draws markers in a plot's viewport in data coordinates
- NhlNDCPolygon - draws a polygon clipped to a plot's viewport in NDC units
- NhlNDCPolyline - draws a line clipped to a plot's viewport in NDC units
- NhlNDCPolymarker - draws markers in a plot's viewport in NDC units
Reference Manual Control Panel
NG4 Home, Index, Examples, Glossary, Feedback, Ref Contents, Ref WhereAmI?