You are here: Home / Services / Data Analysis and Visualization / Visualization / Software / NCL / NCL examples

NCL examples

A collection of NCL example plots and scripts.

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.

If you want to know how to read and plot rectilinear, curvilinear or unstructured data you should have a look at the web page for the EGU 2014 splinter meeting SPM1.12 'Visualization Tools - A light hands-on' NCL examples about rectilinear, curvilinear, unstructured and shapefile data, regridding, and export to a new netCDF file http://www.dkrz.de/Nutzerportal-en/workshops/past-events/EGU2014-Visualization/ncl-light-hands-on-examples-for-egu-2014

  1.  Maps
map resources, functions, select sub-region, overlays,
coastal outlines, map areas
  2.  XY-plots
1D data line plot, timeseries, statistics
  3.  Contour plots
2D data line, color fill (shaded), fill pattern, overlays, slices
  4.  Vector plots
2D vector data, e.g. wind components uv
  5.  Overlays
contour line on filled contour plot, vector on contours,
different grid resolutions
  6.  Annotations
annotations, e.g. text, legends, labelbars, maps, plots
  7.  Panel plots
multiple plots in one frame (page)
  8.  Animations
time depending animations, create single plot for each timestep
  9.  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
10.  Grids
rectilinear, curvilinear, unstructured (ICON, satellite data)
11.  Shapefiles
country outlines, compute temperature means of counties
12.  Analysis
statistics: trend, running mean, averages, zonal mean
13.  Regridding
regrid curvilinear to rectilinear, regrid to higher resolution
14.  Colors
use of pre-defined color maps, named colors and opacity
15.  Write netCDF file
short and detailed version to write data to a new netCDF file
16.  System calls
how to use system function with double-quotes
17.  Command line parameter
how to call/run an NCL script within a Shell script
18. Task parallelism
how use subprocess and subprocess_wait function
19. Miscellaneous
miscellaneous scripts e.g. calendar conversion

  More examples can be found on the NCL examples web page: http://ncl.ucar.edu/Applications/

 


 

1. Maps

 NCL map settings w400

Orthographic projection

NCL overlay small map on map plot w200

Overlay a small world map onto a regional map, annotations

NCL add latitude/longitude annotation to Robinson projection example w400

Robinson projection, add latitude and longitude labels

NCL counts per country map plot example w400

Plot counts per country on a map

 Up


 

2. XY-plots

 NCL xy-plot example

Plot 1D data, set line color blue, PNG output

NCL xy-plot two lines example w400

Plot two variables, use two resource objects and gsn_csm_xy2

NCL multi timeseries example w400

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

NCL xy-plot two time series colorized between stddevs

Plot two time series with 'pseudo stddev' and colorize between the stddev lines

 

 

  Up


 

3. Contour plots

 NCL contour lines w400

Contour line plot

 NCL contour filled w400

Contour fill plot

 

NCL JPEG images as background map overlayed by clouds example w200

 

Contour fill plot with transparency, JPEG file as background image

 

 

 NCL contour curvilinear w400

Curvilinear data

 NCL contour unstructured w400

Unstructured data

NCL slices example w400

Slice Plot, reversed logarithmic y-axis

NCL plot two different grids on a globe w400

Orthographic projection, plot two different grid resolutions, common labelbar

NCL regional map overlayed on global map Satellite projection example w400

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

NCL add latitude/longitude annotation to Robinson projection example w400

Robinson projection, add latitude and longitude labels

  Up


 

4. Vector plots

 NCL vector default w400

Vector plot

 NCL vector colorized w400

Vector plot colored by temperture data

NCL vector overlay w400

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

 

DKRZ NCL example ICON: draw vectors workaround w200

 

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

  Up


 

5. Overlays

NCL vector overlay w400

Vectors overlayed on contour fill plot

NCL bar chart with stats w400

Bar chart plot, running mean and trend are overlayed on data

NCL plot two different grids on a globe w400

Orthographic projection, plot two different grid resolutions, common labelbar

NCL regional map overlayed on global map Satellite projection example w400

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

NCL overlay small map on map plot w200

Overlay a small world map onto a regional map, annotations

 

  Up


 

6. Annotations

NCL multi timeseries example w400

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

NCL bar chart with text w400

Bar chart plot with text next to the bars

NCL overlay small map on map plot w200

Overlay a small world map onto a regional map, annotations
NCL legend settings example w400



NCL legend settings example 4 w400

NCL legend settings example 2 w400

 

 

 

Four plots with different legend settings

NCL legend settings example 3 w400

NCL add text to plot example w400

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

NCL tickmark settings example w400

Change tickmark settings, color, size

NCL font and function code example w400

Text settings, change font, size, color, justification, superscript, subscript

DKRZ NCL data vs. time coordinate variable w200

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

DKRZ NCL example change the x-axis label w200

 

change the x-axis labels

 

  Up


 

7. Panel plots

NCL panel w400

Panel plot, PreDraw, Draw, PostDraw, Mask

  Up


 

8. Animations

 

 

DKRZ NCL animation example

Two spinning globes

 

DKRZ NCL spiral NH example 2006-2100 w800

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


 

9. Special plots

NCL attach plot to another plot along the y-axis example w400

Attach an xy-plot along the right y-axis, slice plot

DKRZ NCL example attached plots among others w200

Attach plots of long timeseries among each other

NCL scatter plot with legend example w400

Scatter plot

NCL bar chart w400

Bar chart plot

NCL bar chart with stats w400

Bar chart plot, running mean and trend are overlayed on data

NCL counts per country map plot example w400

Plot counts per country on a map

NCL bar chart with text w400

Bar chart plot with text next to the bars

NCL JPEG images as background map overlayed by clouds example w200

 

Contour fill plot with transparency, JPEG file as background image

NCL regional map overlayed on global map Satellite projection example w400

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

NCL/ImageMagick tilt a contour plots and compose it to one new image w200

 

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

NCL/ImageMagick KSH script to tilt 3 contour plots and compose them into one new image

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

DKRZ NCL spiral NH example 2006-2100 w800

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

Common colorbar for 4 plots 4 rows by 4 columns

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

 

Common colorbar for 4 plots - Control

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

 

DKRZ NCL Box-Whisker plot w200

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

DKRZ NCL add points of significance to contour plot w200

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

DKRZ NCL Sea Ice Spiral plot w200

Sea Ice Spiral plot based on 'Artic Death Spiral' from Andy Lee Robinson, 2017

DKRZ NCL Germany sunshine duration colored by temperature w200

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

  Up


 

10. Grids

NCL contour filled w400

Rectilinear grid

NCL contour curvilinear w400

Curvilinear grid

NCL contour unstructured w400

Unstructured grid

NCL unrotate CORDEX EUR-11 rotated grid w200

CORDEX EUR-11 grid

NCL REMO plot rotated data example w400REMO regional grid

NCL ICON triangles w400ICON grid

NCL ICON add_polygon triangles

ICON grid

NCL ICON Mollweide projection + add latitude annotation example w400

ICON grid

 

DKRZ NCL ICON contour plot global data using CellFill mode w200

 

ICON grid: contour plot of global data using CellFill mode

NCL FESOM w400

FESOM grid

NCL FESOM topography plot example w400

FESOM grid

 

NCL EUMETSAT IASI original data w400

EUMETSAT IASI swath data

NCL EUMETSAT IASI T63 w400

EUMETSAT IASI regridded to T63 gaussian grid

NCL plot two different grids on a globe w400

Orthographic projection, plot two different grid resolutions, common labelbar

NCL regional map overlayed on global map Satellite projection example w400

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


 

11. Shapefiles

NCL shapefile German Federal States w400

Draw shapefile polyline content

NCL shapefile mean temp German coast w400

Temperature mean of the coastal region of Germany

DKRZ NCL masked data by shapefile w200

Masked data by shapefile

  Up


 

12. Analysis

NCL statistics w400

Running mean and trend

NCL bar chart with stats w400

Bar chart plot, running mean, trend

NCL attach plot to another plot along the y-axis example w400

Attach an xy-plot (zonal mean) along the right y-axis, slice plot

 

 

NCL compute and plot relative differences

Relative differences

 

DKRZ NCL daily climatology w200

Daily climatology

 

DKRZ NCL comparison of NCL and CDO seasons w200

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

  Up


 

13. Regridding

NCL rotated grid w400

ESMF regridding, curvilinear to rectilinear

NCL unrotate CORDEX EUR-11 rotated grid w200

Unrotate CORDEX roteated grid to its origin

NCL EUMETSAT IASI T63 w400

EUMETSAT IASI regridded to T63 gaussian grid

  Up


 

14. Colors

DKRZ colors gsn_define_colormap 01 w200

DKRZ colors gsn_define_colormap 02 w200

 

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

 

DKRZ colors cnFillPalette w200

 

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

 

 

 

DKRZ colors named colors w200

 

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.

 

 

 


 

 

15. Write netCDF file

Export data to new netCDF file: short and simple Export data to new netCDF file: detailed

  Up


 

16. 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


 

17. 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


 

18. 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


 

19. 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


 

Document Actions