The NCAR Command Language (NCL) has a great set of built-in functions, with outstanding documentation, but there are many times when you can speed up your work flow by creating your own library of functions. I’ve been slowly building a library of custom NCL functions that have been really useful over the years. There’s no mechanism for me to get them added to the standard NCL library so I thought the next best thing would to just publish them online and hope other people will find them useful as well.
I almost always use the PNG format when creating figures. I want my figures to look crisp, so I have the default size set pretty large in “~/.hluresfile“:
! Make default X11 window larger (the default is 500x500) *wkWidth : 2048 *wkHeight : 2048
This works great, but the image files always have a ton of white space that makes it difficult to insert them into documents or posters. Since I don’t want to have to manually crop them every time, I wrote a function that I put at the end of every plotting script that autolmatically crops the image for me.
;======================================================================= ;======================================================================= undef("trimPNG") procedure trimPNG(fig_file) local res,cmd begin strver = systemfunc("ncl -V") ver = tofloat(strver) sub = str_sub_str(strver,ver+".","") if .not.isStrSubset(fig_file,".png") then fig_file = fig_file + ".png" end if cmd = "convert -trim "+fig_file+" "+fig_file if (ver.ge.6.2) .or. ((ver.eq.6.2).and.(sub.ge.1)) then if fileexists(fig_file) then system(cmd) end if else if isfilepresent(fig_file) then system(cmd) end if end if print("") print(" "+fig_file) print("") end ;======================================================================= ;=======================================================================
This function relies on the “convert -trim” command from the ImageMagik library, which is freely available and easy to install. This is what actually does the cropping.
The input fig_file can include an extension or not. If the file doesn’t exist, then nothing will happen, but it will still print the file name.
One quirky aspect is that the NCL function to check whether a file exists has changed in recent NCL version. Generally I find newer fileexists() to be the better function, but this didn’t exist in NCL prior to version 6.2.1. So I made sure my function trimPNG() checks the current version of NCL and switches the command accordingly.