NCL examples#

Most of the NCL examples, tipps and tricks have been collected from our NCL user requests. The special examples are developed at DKRZ to support our users and to demonstrate NCL’s capabilities (here NCL version 6.4.0). The used data sets of the example scripts are stored on our supercomputer mistral in the directory /work/kv0653/NCL/data_examples.

Categories#

Maps

map resources, functions, select sub-region, overlays, coastal outlines, map areas

XY-plots

1D data line plot, timeseries, statistics

Contour plots

2D data line, color fill (shaded), fill pattern, overlays, slices

Vector plots

2D vector data, e.g. wind components uv

Overlays

contour line on filled contour plot, vector on contours, different grid resolutions

Annotations

annotations, e.g. text, legends, labelbars, maps, plots

Panel plots

multiple plots in one frame (page)

Animations

time depending animations, create single plot for each timestep

Special Plots

attach plot along y-axis, plot long timeseries, clouds and labelbar with transparency, map areas, spiral plot (Ed Hawkins), simulate 3D view, tilt contour plots using ImageMagick

Grids

rectilinear, curvilinear, unstructured (ICON, satellite data)

Shapefiles

country outlines, compute temperature means of counties

Analysis

statistics: trend, running mean, averages, zonal mean

Regridding

regrid curvilinear to rectilinear, regrid to higher resolution

Colors

use of pre-defined color maps, named colors and opacity

Write netCDF file

short and detailed version to write data to a new netCDF file

System calls

how to use system function with double-quotes

Command line parameter

how to call/run an NCL script within a Shell script

Task parallelism

how use subprocess and subprocess_wait function

Miscellaneous

miscellaneous scripts e.g. calendar conversion


More examples can be found on the examples web page of NCL.


Maps#

NCL map settings Orthographic projection

NCL overlay small map on map plot Overlay a small world map onto a regional map, annotations

NCL add latitude/longitude annotation to Robinson projection example Robinson projection, add latitude and longitude labels

NCL counts per country map plot example Plot counts per country on a map

Up

XY-plots#

NCL xy-plot example Plot 1D data, set line color blue, PNG output

NCL xy-plot two lines example Plot two variables, use two resource objects and gsn_csm_xy2

NCL multi timeseries example Plot multiple timeseries (1D data), create a legend, change line color, line dash pattern, annotations

image7 Plot two time series with ‘pseudo stddev’ and colorize between the stddev lines

image8 image9 Change the y-axis scaling from standard regular to irregular grid area weighted values, here latitude

Up

Contour plots#

NCL contour lines Contour line plot

NCL contour filled Contour fill plot

NCL JPEG images as background map overlayed by clouds example Contour fill plot with transparency, JPEG file as background image

NCL contour curvilinear Curvilinear data

NCL contour unstructured Unstructured data

NCL slices example Slice Plot, reversed logarithmic y-axis

NCL plot two different grids on a globe Orthographic projection, plot two different grid resolutions, common labelbar

image17 Satellite projection, change background/foreground color, draw a shadow, common labelbar

NCL add latitude/longitude annotation to Robinson projection example Robinson projection, add latitude and longitude labels

Up

Vector plots#

NCL vector default Vector plot

NCL vector colorized Vector plot colored by temperture data

NCL vector overlay Vector plot overlayed on contour fill plot

NCL vectors on a curvilinear grid example Vectors on curvilinear grid, draw edges in blue, draw edges of missing values in gray

image22 ICON (unstructured grid): workaround to draw vectors on center latitudes/longitudes

Up

Overlays#

NCL vector overlay Vectors overlayed on contour fill plot

NCL bar chart with stats Bar chart plot, running mean and trend are overlayed on data

NCL plot two different grids on a globe Orthographic projection, plot two different grid resolutions, common labelbar

image24 Satellite projection, change background/foreground color, draw a shadow, common labelbar

NCL overlay small map on map plot Overlay a small world map onto a regional map, annotations

Up

Annotations#

NCL multi timeseries example Plot multiple timeseries (1D data), create a legend, change line color, line dash pattern, annotations

NCL bar chart with text Bar chart plot with text next to the bars

NCL overlay small map on map plot Overlay a small world map onto a regional map, annotations

NCL legend settings example NCL legend settings example 4

NCL legend settings example 2 Four plots with different legend settings

NCL legend settings example 3

NCL add text to plot example Add text to a plot, superscript, subscript, German Umlaute, Text background

NCL tickmark settings example Change tickmark settings, color, size

NCL font and function code example Text settings, change font, size, color, justification, superscript, subscript

image33 Data vs. time - how to use the time coordinate variable (x-axis) correct

image34 Change the x-axis labels

Up

Panel plots#

NCL panel Panel plot, PreDraw, Draw, PostDraw, Mask

image36 Multiple plots on one page

Up

Animations#

DKRZ NCL animation example Two spinning globes

image38 Animation of multi-year monthly mean temperature change data similar to Ed Hawkins’s spiral animation (https://www.climate-lab-book.ac.uk/spirals/)

Up

Special plots#

NCL attach plot to another plot along the y-axis example Attach an xy-plot along the right y-axis, slice plot

image40 Attach plots of long timeseries among each other

NCL scatter plot with legend example Scatter plot

NCL bar chart Bar chart plot

NCL bar chart with stats Bar chart plot, running mean and trend are overlayed on data

NCL counts per country map plot example Plot counts per country on a map

NCL bar chart with text Bar chart plot with text next to the bars

NCL JPEG images as background map overlayed by clouds example Contour fill plot with transparency, JPEG file as background image

image43 Satellite projection, change background/foreground color, draw a shadow, common labelbar

image44 Tilt a contour plot, compose title, plot and labelbar, resize the new image, KSH-script

image45 Tilt 3 contour plots, compose title, plot and labelbar, add level labels and resize the new image, KSH-script

image38 Animation of multi-year monthly mean temperature change data similar to Ed Hawkins’s spiral animation (https://www.climate-lab-book.ac.uk/spirals/)

image47 Draw a common labelbar for 4 overlayed plots using 4 rows by 4 columns

image48 Just to see how the 4 single plots from the example before look like

image49 Panel plot using vp-resources. Box-Whisker plot with filled boxes and labels (separate modified boxplot function).

NCL significance Add significance (sig=1) as points to contour plot

image50 Sea Ice Spiral plot based on ‘Artic Death Spiral’ from Andy Lee Robinson, 2017

image51 Bar chart plot of Germany’s sunshine duration hour per year colored by the annual average temperature

image52 Scatter plot with two attached histograms

image53 image54 Draw data using marker with the size depending on another variable

Up

Grids#

NCL contour filled Rectilinear grid

NCL contour curvilinear Curvilinear grid

NCL contour unstructured Unstructured grid

NCL unrotate CORDEX EUR-11 rotated grid CORDEX EUR-11 grid

NCL REMO plot rotated data example REMO regional grid

NCL ICON triangles ICON grid

NCL ICON add_polygon triangles ICON grid

NCL ICON Mollweide projection + add latitude annotation example ICON grid, Mollweide, map annotation

image60 ICON grid: contour plot of global data using CellFill mode

NCL FESOM FESOM grid

NCL FESOM topography plot example FESOM grid

NCL EUMETSAT IASI original data EUMETSAT IASI swath data

NCL EUMETSAT IASI T63 EUMETSAT IASI regridded to T63 gaussian grid

NCL plot two different grids on a globe Orthographic projection, plot two different grid resolutions, common labelbar

image65 Satellite projection, change background/foreground color, draw a shadow, common labelbar

NCL select sub-region of curvilinear data Curvilinear grid, sub-region, attach gridlines

Up

Shapefiles#

NCL shapefile German Federal States Draw shapefile polyline content

NCL shapefile mean temp German coast Temperature mean of the coastal region of Germany

image69 Masked data by shapefile

image70 Use a shapefile for masking

image71 Use parts of a shapefile for masking

Up

Analysis#

NCL statistics Running mean and trend

NCL bar chart with stats Bar chart plot, running mean, trend

NCL attach plot to another plot along the y-axis example Attach an xy-plot (zonal mean) along the right y-axis, slice plot

image73 Relative differences

image74 Daily climatology

image75 Comparison of NCL and CDO seasons DJF, MAM, JJA, SON

Up

Regridding#

NCL rotated grid ESMF regridding, curvilinear to rectilinear

NCL unrotate CORDEX EUR-11 rotated grid Unrotate CORDEX roteated grid to its origin

NCL EUMETSAT IASI T63 EUMETSAT IASI regridded to T63 gaussian grid

Up

Colors#

image77 Demonstrate the use gsn_define_colormap() to set a color map for all plots of a frame (file/page)

image78 Demonstrate the use of cnFillPalette to set the color map for a plot which can be different for each plot in the same frame

image79 Demonstrate the use of named colors to define a color map. Use the reversed color map of the upper plot for the lower plot within the same frame

Up

Write netCDF file#

Export data to new netCDF file: short and simple

Export data to new netCDF file: detailed

Up

System calls#

system or systemfunc call with double quotes

To execute a UNIX shell command  within an NCL script the built-in system procedure or the systemfunc function can be used.

system("date")
datestring = systemfunc("date")

To execute a shell command using double quotes itself you have to do a little trick to get the correct result. For example:

system("date "+DATE: %Y-%m-%d%nTIME: %H:%M:%S"")

will cause an error like

fatal:syntax error: function systemfunc expects 1 arguments, got 0
fatal:error at line 67 in file systemfunc_pass_variables.ncl

fatal:syntax error: line 71 in file systemfunc_pass_variables.ncl before or near :
system("date "+DATE:
-------------------^

fatal:error in statement
fatal:Syntax Error in block, block not executed
fatal:error at line 73 in file systemfunc_pass_variables.ncl

The trick is to define the double quote character as a variable with the built-in function str_get_dq() and use this variable with the concatenation operator + to create the command string for system or systemfunc:

quote = str_get_dq()

datestring = systemfunc("date "+quote+"+DATE: %Y-%m-%d%nTIME: %H:%M:%S"+quote+" ")
print(datestring)

Up

Command line parameter#

Run an NCL script from a shell script

csh/tcsh snippet:

...
set cnfill  = "True"
set country = "True"

set cmin  =  255.0
set cmax  =  300.0
set cint  =  1

ncl -n -Q country=\""$country"\" \
          cnfill=\""$cnfill"\" \
          contours=\""${cmin},${cmax},${cint}"\" \
          calls_from_batch_job_NCL_script.ncl
...

NCL script snippet:

...
  if(isvar("cnfill")) then                              ;-- is 'cnfill' on command line?
     mres@cnFillOn          =  True                     ;-- turn on color fill
     mres@cnFillPalette     = "rainbow"
     mres@cnLineLabelsOn    =  False
     mres@cnInfoLabelOn     =  False
     mres@cnLinesOn         =  False
  end if

  if(isvar("country") .and. country .eq. "True") then   ;-- is 'country' on command line?
     mres@mpOutlineBoundarySets =  "National"           ;-- draw national outlines
  end if

  if(isvar("contours")) then                            ;-- is 'contours' on command line?
     cmin  = tofloat(str_get_field(contours,1,","))
     cmax  = tofloat(str_get_field(contours,2,","))
     cint  = tofloat(str_get_field(contours,3,","))
     mres@cnLevelSelectionMode = "ManualLevels"         ;-- contour min, max and interval
     mres@cnMinLevelValF   =  cmin
     mres@cnMaxLevelValF   =  cmax
     mres@cnLevelSpacingF  =  cint
  else                                                  ;-- set defaults
     cmin  = min(data)
     cmax  = max(data)
     clevs = 18
     mnmxint = nice_mnmxintvl( cmin, cmax, clevs, False)
     mres@cnLevelSelectionMode = "ManualLevels"
     mres@cnMinLevelValF   =  mnmxint(0)
     mres@cnMaxLevelValF   =  mnmxint(1)
     mres@cnLevelSpacingF  =  mnmxint(2)
  end if
...

Up

Task parallelism#

Use an NCL script to start running multiple NCL plot scripts at one time in parallel.

The main script running multiple plot scripts using the subprocess function and wait until their are finished using subprocess_wait.

;---------------------------------------------------------------
;  main_subprocess.ncl
;
;  Use the subprocess and subprocess_wait functions to generate
;  the time dependend PNG plots to create an animation.
;
;  This script is calling the plot script
;                 plot_script.ncl
;
;  Use the max_processes variable to set the number of processes
;  running in parallel. A number equal to the number of processor
;  cores can be a good choice.
;---------------------------------------------------------------
begin
  st = get_cpu_time()

;-- create a directory for the plots, if it doesn't exit
  system("mkdir -p test_subprocess_images")

;-- initialize number of timesteps and set maximum number of processes
;  ntsteps       = -1
  max_processes = 8

;-- open the file and retrieve the number of timesteps
  f    = addfile("rectilinear_grid_2D.nc", "r")
  time = f->time

  ntsteps = dimsizes(time)
  print("timesteps: "+ntsteps)

  ndone   = 0
  nactive = 0

;-- only max_processes at a time
  do i=0,ntsteps-1
     do while (nactive .ge. max_processes)
        pid = subprocess_wait(0,True)   ;-- check for completition
        if (pid .gt. 0) then
           ndone   = ndone + 1
           nactive = nactive - 1
           break
        end if
     end do

     print("plot: "+i)

     cmd = "ncl plot_script.ncl " + str_get_sq() + "tstep=" + i + str_get_sq() + " >/dev/null"

     pid = subprocess(cmd)

     nactive = nactive+1
  end do

;-- check if we have to wait until all jobs are done
  do while (ndone.lt.ntsteps-1)
     pid = subprocess_wait(0,True)      ;-- check for completition
     if (pid.gt.0) then
        ndone = ndone + 1
     end if
  end do

;-- how long does it take
  et = get_cpu_time()
  print("--> Plots CPU time:  "+ (et-st) + " seconds")

;-- create the animated GIF file
  system("cd test_subprocess_images; convert -delay 100 -loop 0 plot_tsurf*.png animation.gif")

;-- that's it
  et = get_cpu_time()
  print("--> GIF CPU time:    "+ (et-st) + " seconds")

end

Plot script called by the main script:

;---------------------------------------------------------------
;  plot_script.ncl
;
;  Create a contour plot of variable tsurf at a given time and
;  save it to the directory test_subprocess_images. For each time
;  step the variable tstep has to be given on the command line.
;---------------------------------------------------------------
begin
  f     = addfile("rectilinear_grid_2D.nc","r")
  var   = f->tsurf(tstep,:,:)

  date  = cd_calendar(f->time(tstep),0)
  title = sprinti("%04d",toint(date(0,1)))+"/"+sprinti("%4d",toint(date(0,0)))

  pltname = "test_subprocess_images/plot_tsurf"+sprinti("%04d",tstep)

  wks = gsn_open_wks("png",pltname)

  res                          =  True
  res@gsnMaximize              =  True

  res@tiMainString             =  title

  res@cnFillOn                 =  True

  res@lbOrientation            = "Vertical"
  res@pmLabelBarOrthogonalPosF =  -0.02

  plot = gsn_csm_contour_map(wks,var,res)

end

Up

Miscellaneous#

Several helpful scripts e.g. to convert data using Julian calendar to a standard calendar.

a) Convert data using Julian calendar to standard calendar –> script

Up