Exemple #1
0
 def add_polymarker(wks, plot, xd, yd, index, size, thick, color):
     """https://www.ncl.ucar.edu/Document/Functions/Built-in/NhlNewMarker.shtml"""
     poly_res = Ngl.Resources()
     poly_res.gsMarkerIndex = index  #4   # choose circle as polymarker
     poly_res.gsMarkerSizeF = size  # select size to avoid streaking
     poly_res.gsMarkerThicknessF = thick  #30.0
     #poly_res.gsMarkerOpacityF = 0.3
     poly_res.gsMarkerColor = color  #purple4 # choose color
     return Ngl.add_polymarker(wks, plot, xd, yd, poly_res)
Exemple #2
0
def add_trajectories(wks,map,filename,cmap):
#---Open the netCDF file containing the salinity data for the trajectories.
  ncfile = Nio.open_file(filename)

  traj = [1,10,53,67,80]   # choose which trajectories to plot
   
  pres                  = Ngl.Resources()    # polyline resources
  pres.gsLineThicknessF = 5.0                # line thickness

  mres  = Ngl.Resources()                    # marker resources
  mres.gsMarkerSizeF       = 17.0            # marker size
  mres.gsMarkerColor       = "black"         # marker color
  mres.gsMarkerIndex       = 15              # circle with an X
  mres.gsMarkerThicknessF  = 2.0             # thicker marker outlines

#
#  Loop through the chosen trajectories.
#
  sdata = ncfile.variables["sdata"]
  sid = []
  for i in range(len(traj)):
    lat = sdata[2,:,traj[i]]                  # extract lat from whole array
    lon = sdata[1,:,traj[i]]                  # extract lon from whole array
    sst = sdata[8,:,traj[i]]

#
#  Map the salinity values between 34.55 and 34.85 into color
#  indices between 0 and 9 and draw polylines, with those 
#  colors, between adjacent lat/lon values.
#
    for j in range(len(lat)-2):
      sval = 0.5*(sst[j]+sst[j+1])
      cindex = nint(30.*(sval-34.55))
      pres.gsLineColor = cmap[cindex]
      sid.append(Ngl.add_polyline(wks,map,[lon[j],lon[j+1]],[lat[j],lat[j+1]],pres))

#---Draw a polymarker at the beginning of each trajectory.
      sid.append(Ngl.add_polymarker(wks,map,[lon[0]],[lat[0]],mres))

  return
Exemple #3
0
def add_masked_grid(wks,plot,lat,lon,mask):
#
# Create 2D arrays of lat/lon so we can draw markers outside the 
# masked area
#
  nlat  = len(lat)
  nlon  = len(lon)
  lat2d = numpy.tile(lat,nlon)
  lat2d = numpy.reshape(lat2d,[nlon,nlat])
  lat2d = numpy.transpose(lat2d)
  lon2d = numpy.tile(lon,nlat)
  lon2d = numpy.reshape(lon2d,[nlat,nlon])

  lat1d_mask = ma.ravel(ma.masked_where(mask==0,lat2d))
  lon1d_mask = ma.ravel(ma.masked_where(mask==0,lon2d))

  mkres               = Ngl.Resources()
  mkres.gsMarkerIndex = 16          # filled dot
  mkres.gsMarkerSizeF = 0.003
  mkres.gsMarkerColor = "purple"

  return Ngl.add_polymarker(wks,plot,lon1d_mask,lat1d_mask,mkres)
Exemple #4
0
#
#  Transpose the array so we can plot it, because Natgrid returns it
#  as an X x Y array, rather than Y x X which PyNGL expects.
#
zt = numpy.transpose(zo)

contour = Ngl.contour(wks,zt,resources)

#
# Add some polymarkers showing the original locations of the X,Y points.
#
poly_res               = Ngl.Resources()
poly_res.gsMarkerIndex = 16
poly_res.gsMarkerSizeF = 0.015
Ngl.add_polymarker(wks,contour,x,y,poly_res)

Ngl.draw(contour)
Ngl.frame(wks)


#
# Now turn on RasterFill for the contours and compare.
#
resources.tiMainString          = "Interpolation to a 2D grid (RasterFill)"
resources.cnFillMode            = 'RasterFill'
contour                         = Ngl.contour(wks,zt,resources)

#
#  Draw polymarkers again.
#
#-- add polygon and polyline to map
gon_2 = Ngl.add_polygon(wks, map, x, y, pres)
plres.gsLineColor = "darkorange"  #-- set line color
box_2 = Ngl.add_polyline(wks, map, x, y, plres)

#----------------------------------------------------------------
#-- polymarker resources
#----------------------------------------------------------------
pmres = Ngl.Resources()
pmres.gsMarkerColor = "blue"  #-- marker color
pmres.gsMarkerIndex = 1  #-- use marker 1
pmres.gsMarkerSizeF = 0.03  #-- set size of marker
pmres.gsLineThicknessF = 8.  #-- marker line thickness

#-- unique identifier name for polymarker drawing, here marker_1
marker_1 = Ngl.add_polymarker(wks, map, -100., 30., pmres)

#----------------------------------------------------------------
#-- draw all 16 marker on plot using unique identifier name and
#-- additional map attribute settings
#----------------------------------------------------------------
x = -160.  #-- x-position of first marker
y = -80.  #-- y-position of first marker
idstr = "poly"

for i in range(0, 16):  #-- 16 different marker
    pmres.gsMarkerIndex = i + 1
    id = idstr + str(i)  #-- result is poly0-poly15
    #-- add marker to map
    map.id = Ngl.add_polymarker(wks, map, x + (i * 20.), y + (i * 10.), pmres)
Exemple #6
0
def draw_2D_plot(ptype, cseason, ncases, cases, casenames, nsite, lats, lons,
                 filepath, filepathobs, casedir):

    # ncases, the number of models
    # cases, the name of models
    # casename, the name of cases
    # filepath, model output filepath
    # filepathobs, filepath for observational data
    # inptrs = [ncases]
    if not os.path.exists(casedir):
        os.mkdir(casedir)

    if not os.path.exists(casedir + '/2D'):
        os.mkdir(casedir + '/2D')

    _Font = 25
    interp = 2
    extrap = False
    infiles = ['' for x in range(ncases)]
    ncdfs = ['' for x in range(ncases)]
    alpha = ['A', 'B', 'C', 'D', 'E', 'F']
    cunits = ['']
    varis = [
        'SWCF', 'LWCF', 'PRECT', 'LHFLX', 'SHFLX', 'TMQ', 'PS', 'TS', 'U10',
        'CLDTOT', 'CLDLOW', 'CLDHGH', 'TGCLDLWP'
    ]
    varisobs = [
        'SWCF', 'LWCF', 'PRECT', 'LHFLX', 'SHFLX', 'PREH2O', 'PS', 'TS', 'U10',
        'CLDTOT_CAL', 'CLDTOT_CAL', 'CLDTOT_CAL', 'TGCLDLWP_OCEAN'
    ]
    nvaris = len(varis)
    cscale = [1, 1, 86400000, 1, 1, 1, 1, 1, 1, 100, 100, 100, 1000, 1, 1, 1]
    cscaleobs = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    # cntrs = [[0 for col in range(11)] for row in range(nvaris)]
    cntrs = np.zeros((nvaris, 11), np.float32)

    obsdataset = [
        'CERES-EBAF', 'CERES-EBAF', 'GPCP', 'ERAI', 'NCEP', 'ERAI', 'NCEP',
        'ERAI', 'ERAI', 'CALIPSOCOSP', 'CALIPSOCOSP', 'CALIPSOCOSP', 'NVAP'
    ]

    plot2d = ['' for x in range(nvaris)]
    for iv in range(0, nvaris):
        # make plot for each field
        if (varis[iv] == 'CLDTOT' or varis[iv] == 'CLDLOW'
                or varis[iv] == 'CLDHGH'):
            cntrs[iv, :] = [2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90]
        if (varis[iv] == 'LWCF'):
            cntrs[iv, :] = [1, 2, 5, 10, 15, 20, 25, 30, 35, 40, 45]
        if (varis[iv] == 'SWCF' or varis[iv] == 'FLUT'):
            cntrs[iv, :] = [
                -40, -50, -60, -70, -80, -90, -100, -110, -120, -130, -140
            ]
        if (varis[iv] == 'PRECT' or varis[iv] == 'QFLX'):
            cntrs[iv, :] = [0.5, 1.5, 3, 4.5, 6, 7.5, 9, 10.5, 12, 13.5, 15]
        if (varis[iv] == 'LHFLX'):
            cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
        if (varis[iv] == 'SHFLX'):
            cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
        if (varis[iv] == 'U10'):
            cntrs[iv, :] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
        if (varis[iv] == 'TMQ'):
            cntrs[iv, :] = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55]
        if (varis[iv] == 'TGCLDLWP'):
            cntrs[iv, :] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]

#  Observational data
        if (obsdataset[iv] == 'CCCM'):
            if (cseason == 'ANN'):
                fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-' + cseason + '.nc'
            else:
                fileobs = '/Users/guoz/databank/CLD/CCCm/cccm_cloudfraction_2007-2010-' + cseason + '.nc'
        else:
            if (varisobs[iv] == 'PRECT'):
                fileobs = filepathobs + '/GPCP_' + cseason + '_climo.nc'
            else:
                fileobs = filepathobs + obsdataset[
                    iv] + '_' + cseason + '_climo.nc'

#       infiles[im]=filepath[im]+cases[im]+'/run/'+cases[im]+'_'+cseason+'_climo.nc'

        inptrobs = Dataset(fileobs, 'r')
        latobs = inptrobs.variables['lat'][:]
        lonobs = inptrobs.variables['lon'][:]
        if (varisobs[iv] == 'U10'):
            B0 = inptrobs.variables[varisobs[iv]][0, :, :]
            B1 = inptrobs.variables['V10'][0, :, :]
            B = (B0 * B0 + B1 * B1)
            B = B * cscaleobs[iv]
            B = np.sqrt(B)
        else:
            B = inptrobs.variables[varisobs[iv]][0, :, :]
            B = B * cscaleobs[iv]

        #************************************************
        # create plot
        #************************************************
        plotname = casedir + '/2D/Horizontal_' + varis[iv] + '_' + cseason
        plot2d[iv] = 'Horizontal_' + varis[iv] + '_' + cseason
        wks = Ngl.open_wks(ptype, plotname)
        Ngl.define_colormap(wks, 'cmocean_thermal')
        #   Ngl.define_colormap(wks,'MPL_coolwarm')

        #   ngl_define_colormap(wks,'prcp_1')
        plot = []

        textres = Ngl.Resources()
        textres.txFontHeightF = 0.02  # Size of title.
        textres.txFont = _Font
        Ngl.text_ndc(wks, varis[iv], 0.1, .97, textres)

        pres = Ngl.Resources()
        pres.nglMaximize = True
        pres.nglPanelYWhiteSpacePercent = 5
        pres.nglPanelXWhiteSpacePercent = 5
        pres.nglPanelBottom = 0.20
        pres.nglPanelTop = 0.9
        pres.pmLabelBarWidthF = 0.8
        pres.nglFrame = False
        pres.nglPanelLabelBar = True  # Turn on panel labelbar
        pres.nglPanelLabelBarLabelFontHeightF = 0.015  # Labelbar font height
        pres.nglPanelLabelBarHeightF = 0.0750  # Height of labelbar
        pres.nglPanelLabelBarWidthF = 0.700  # Width of labelbar
        pres.lbLabelFont = 'helvetica-bold'  # Labelbar font
        pres.nglPanelTop = 0.935
        pres.nglPanelFigureStrings = alpha
        pres.nglPanelFigureStringsJust = 'BottomRight'

        res = Ngl.Resources()
        res.nglDraw = False  #-- don't draw plots
        res.nglFrame = False
        res.cnFillOn = True
        res.cnFillMode = 'RasterFill'
        res.cnLinesOn = False
        res.nglMaximize = True
        res.mpFillOn = True
        res.mpCenterLonF = 180
        res.tiMainFont = _Font
        res.tiMainFontHeightF = 0.025
        res.tiXAxisString = ''
        res.tiXAxisFont = _Font
        res.tiXAxisFontHeightF = 0.025
        res.tiYAxisString = ''
        res.tiYAxisFont = _Font
        res.tiYAxisOffsetXF = 0.0
        res.tiYAxisFontHeightF = 0.025
        res.tmXBLabelFont = _Font
        res.tmYLLabelFont = _Font
        res.tiYAxisFont = _Font
        res.vpWidthF = 0.80  # set width and height
        res.vpHeightF = 0.40
        res.vpXF = 0.04
        res.vpYF = 0.30

        res.cnInfoLabelOn = False
        res.cnFillOn = True
        res.cnLinesOn = False
        res.cnLineLabelsOn = False
        res.lbLabelBarOn = False

        #   res.vcRefMagnitudeF = 5.
        #   res.vcMinMagnitudeF = 1.
        #   res.vcRefLengthF    = 0.04
        #   res.vcRefAnnoOn     = True#False
        #   res.vcRefAnnoZone   = 3
        #   res.vcRefAnnoFontHeightF = 0.02
        #   res.vcRefAnnoString2 =''
        #   res.vcRefAnnoOrthogonalPosF   = -1.0
        #  res.vcRefAnnoArrowLineColor   = 'blue'         # change ref vector color
        #  res.vcRefAnnoArrowUseVecColor = False
        #   res.vcMinDistanceF  = .05
        #   res.vcMinFracLengthF         = .
        #   res.vcRefAnnoParallelPosF    =  0.997
        #   res.vcFillArrowsOn           = True
        #   res.vcLineArrowThicknessF    =  3.0
        #   res.vcLineArrowHeadMinSizeF   = 0.01
        #   res.vcLineArrowHeadMaxSizeF   = 0.03
        #   res.vcGlyphStyle              = 'CurlyVector'     # turn on curley vectors
        #  res@vcGlyphStyle              ='Fillarrow'
        #   res.vcMonoFillArrowFillColor = True
        #   res.vcMonoLineArrowColor     = True
        #   res.vcLineArrowColor          = 'green'           # change vector color
        #   res.vcFillArrowEdgeColor      ='white'
        #   res.vcPositionMode            ='ArrowTail'
        #   res.vcFillArrowHeadInteriorXF =0.1
        #   res.vcFillArrowWidthF         =0.05           #default
        #   res.vcFillArrowMinFracWidthF  =.5
        #   res.vcFillArrowHeadMinFracXF  =.5
        #   res.vcFillArrowHeadMinFracYF  =.5
        #   res.vcFillArrowEdgeThicknessF = 2.0
        res.mpFillOn = False

        res.cnLevelSelectionMode = 'ExplicitLevels'

        res.cnLevels = cntrs[iv][:]

        for im in range(0, ncases):
            ncdfs[im] = './data/' + cases[im] + '_site_location.nc'
            infiles[im] = filepath[im] + cases[im] + '/' + cases[
                im] + '_' + cseason + '_climo.nc'
            inptrs = Dataset(infiles[im], 'r')  # pointer to file1
            lat = inptrs.variables['lat'][:]
            nlat = len(lat)
            lon = inptrs.variables['lon'][:]
            nlon = len(lon)
            area = inptrs.variables['area'][:]

            area_wgt = np.zeros(nlat)

            sits = np.linspace(0, nsite - 1, nsite)
            ncdf = Dataset(ncdfs[im], 'r')
            n = ncdf.variables['n'][:]
            idx_cols = ncdf.variables['idx_cols'][:]
            if (varis[iv] == 'PRECT'):
                A = inptrs.variables['PRECC'][
                    0, :] + inptrs.variables['PRECL'][0, :]
            else:
                A = inptrs.variables[varis[iv]][0, :]

            if (varis[iv] == 'FLUT'):
                A = inptrs.variables['FLUT'][0, :] - inptrs.variables['FLNS'][
                    0, :]
            else:
                A = inptrs.variables[varis[iv]][0, :]

            if (varis[iv] == 'U10'):
                A = inptrs.variables['U10'][0, :] * inptrs.variables['U10'][
                    0, :]
                A = np.sqrt(A)
            else:
                A = inptrs.variables[varis[iv]][0, :]

            A_xy = A
            A_xy = A_xy * cscale[iv]
            ncdf.close()
            inptrs.close()

            if im == 0:
                dsizes = len(A_xy)
                field_xy = [[0 for col in range(dsizes)]
                            for row in range(ncases)]

            field_xy[im][:] = A_xy

            res.lbLabelBarOn = False
            if (np.mod(im, 2) == 0):
                res.tiYAxisOn = True
            else:
                res.tiYAxisOn = False

            res.tiXAxisOn = False
            res.sfXArray = lon
            res.sfYArray = lat
            res.mpLimitMode = 'LatLon'
            res.mpMaxLonF = max(lon)
            res.mpMinLonF = min(lon)
            res.mpMinLatF = min(lat)
            res.mpMaxLatF = max(lat)
            res.tiMainString = 'GLB=' + str(
                np.sum(A_xy[:] * area[:] / np.sum(area)))
            textres.txFontHeightF = 0.015
            Ngl.text_ndc(wks, alpha[im] + '  ' + casenames[im], 0.3,
                         .135 - im * 0.03, textres)

            p = Ngl.contour_map(wks, A_xy, res)
            plot.append(p)

# observation
#   res.nglLeftString = obsdataset[iv]
#  res@lbLabelBarOn = True
#  res@lbOrientation        = 'vertical'         # vertical label bars
        res.lbLabelFont = _Font
        res.tiYAxisOn = True
        res.tiXAxisOn = True
        res.tiXAxisFont = _Font
        rad = 4.0 * np.arctan(1.0) / 180.0
        re = 6371220.0
        rr = re * rad

        dlon = abs(lonobs[2] - lonobs[1]) * rr
        dx = dlon * np.cos(latobs * rad)
        jlat = len(latobs)
        dy = np.zeros(jlat, dtype=float)
        # close enough
        dy[0] = abs(lat[2] - lat[1]) * rr
        dy[1:jlat - 2] = abs(lat[2:jlat - 1] - lat[0:jlat - 3]) * rr * 0.5
        dy[jlat - 1] = abs(lat[jlat - 1] - lat[jlat - 2]) * rr
        area_wgt = dx * dy  #
        is_SE = False

        sum1 = 0
        sum2 = 0

        for j in range(0, jlat - 1):
            for i in range(0, len(lonobs) - 1):
                if (np.isnan(B[j][i]) != '--'):
                    sum1 = sum1 + area_wgt[j] * B[j][i]
                    sum2 = sum2 + area_wgt[j]

        glb = sum1 / sum2
        res.sfXArray = lonobs
        res.sfYArray = latobs
        res.mpLimitMode = 'LatLon'
        res.mpMaxLonF = max(lonobs)
        res.mpMinLonF = min(lonobs)
        res.mpMinLatF = min(latobs)
        res.mpMaxLatF = max(latobs)
        res.tiMainString = 'GLB=' + str(glb)

        p = Ngl.contour_map(wks, B, res)
        if (iv == 0):
            poly_res = Ngl.Resources()
            poly_res.gsMarkerIndex = 16
            poly_res.gsMarkerSizeF = 0.005
            poly_res.gsMarkerColor = 'green'
            dum = Ngl.add_polymarker(wks, p, lons, lats, poly_res)

        plot.append(p)

        if (np.mod(ncases + 1, 2) == 1):
            Ngl.panel(wks, plot[:], [(ncases + 1) / 2 + 1, 2], pres)
        else:
            Ngl.panel(wks, plot[:], [(ncases + 1) / 2, 2], pres)
        Ngl.frame(wks)
        Ngl.destroy(wks)


#   Ngl.end()
    return plot2d
Exemple #7
0
#
# Add primitives to plot.  They will be drawn in the order
# they are added, so some primitives may cover other ones.
#
# Be sure to use unique variable names on the left-hand side
# for the Ngl.add_polyxxxx routines.
#
prim1 = Ngl.add_polyline(wks, xy1, xx, ymidline, gsres)
prim2 = Ngl.add_polygon(wks, xy1, xsquare, ysquare, gsres)
prim3 = Ngl.add_polyline(wks, xy1, xx, ytopline, gsres)
prim4 = Ngl.add_polyline(wks, xy1, xx, ybotline, gsres)

gsres.gsLineColor = "Green"
prim5 = Ngl.add_polyline(wks, xy1, x[26:37], y[26:37], gsres)
prim6 = Ngl.add_polymarker(wks, xy1, xdots, ydots, gsres)

#
# New Y points for second XY plot.
#
y = numpy.cos(3.14159 * x / 32.)

# Create second XY plot, but don't draw it yet.

xy2 = Ngl.xy(wks, x, y, xyres)

#
# Add primitives to second plot.
#
gsres.gsLineColor = "Blue"
Exemple #8
0
cfres.mpGridAndLimbOn           = False         # Turn off grid and limb lines.

pmres.gsMarkerSizeF =  0.0015
pmres.gsMarkerThicknessF = 0.1
pmres.gsMarkerOpacityF = 1

txres    = Ngl.Resources()
txres.txJust = "BottomCenter"
txres.txFontHeightF = 0.025

title = 'Time of emergegence of FWI>p95 frequency~C~1-sigma above all forcing '+str(pyear0[base_pp])+'-'+str(pyear1[base_pp]) 

diff_cyc, lon_cyc = Ngl.add_cyclic(toe_diff_median_masked,lon)
cfres.sfXArray = lon_cyc

cfres.tiMainString      = sf_list[ss]
plot = Ngl.contour_map(wks,diff_cyc,cfres)
pmres.gsMarkerColor = colors[np.int(ncolors/4),:] 
pmres.gsMarkerIndex = 1
marker_all = Ngl.add_polymarker(wks,plot,lon_1d_all,lat_1d_all,pmres)
pmres.gsMarkerColor = colors[np.int(ncolors/4)*3,:] 
pmres.gsMarkerIndex = 1
marker_sf = Ngl.add_polymarker(wks,plot,lon_1d_sf,lat_1d_sf,pmres)

Ngl.draw(plot)
Ngl.text_ndc(wks,title,0.5,0.87,txres)
Ngl.frame(wks)

Ngl.delete_wks(wks)

Exemple #9
0
mkres = Ngl.Resources()
mkres.gsMarkerIndex = 2
mkres.gsMarkerColor = "Brown"

Ngl.polymarker(wks, map, lon, lat, mkres)

Ngl.frame(wks)

#-- second plot
res.mpMinLatF = 22.
res.mpMaxLatF = 60.
res.mpMinLonF = -125.
res.mpMaxLonF = -65.

map = Ngl.map(wks, res)  #-- create the map plot, don't draw

#-- Now attach the markers to the plot and notice that you don't
#-- see them until you draw the plot.
#-- If you resize the plot, the markers will be resized accordingly.
mkres.gsMarkerColor = "Blue"
mkres.gsMarkerSizeF = 15.  #-- increase marker sizes

dum = Ngl.add_polymarker(wks, map, lon, lat, mkres)

#-- draw map and advance the frame
Ngl.draw(map)
Ngl.frame(wks)

Ngl.end()
Exemple #10
0
resources.nglFrame = False
resources.nglDraw = False
resources.mpOutlineBoundarySets = "GeophysicalAndUSStates"
resources.mpLandFillColor = 16
resources.mpFillOn = True
resources.sfXArray = lon
resources.sfYArray = lat
resources.cnFillPalette = "WhViBlGrYeOrRe"
resources.cnLevelSelectionMode = "ExplicitLevels"
resources.cnLevels = np.arange(1, 100, 10)
resources.tiMainString = track_name + " maxwind "
resources.lbTitleString = "Knots"
#resources.lbTitlePosition = "Right"
resources.lbLabelFontHeightF = 0.02
resources.lbTitleFontHeightF = 0.02
resources.cnFillMode = "RasterFill"

mpid = Ngl.contour_map(wks, np.transpose(maxwind), resources)
#mpid = Ngl.contour_map(wks, np.transpose(grid), resources)

mkres = Ngl.Resources()
mkres.gsMarkerIndex = 1
mkres.gsMarkerColor = "Black"
mkres.gsMarkerSizeF = 15
dum = Ngl.add_polymarker(wks, mpid, lon_c, lat_c, mkres)

Ngl.draw(mpid)
Ngl.frame(wks)

Ngl.end()
def plot_psiyr(wks,data,vx,vy,xlab='Latitude [deg N]',ylab = 'y',\
               vsurf=[],hei=0.1,ylon=True,xon=False,lbar=False,flipy=False,\
               vpx=0.15,vpy=0.8,lsmooth=False):
   """
   Plots meridional overturning stream functions
   
   Usage: 
      plot_psiyr(wks,data,vx,vy,xlab='Latitude',ylab='y',vsurf=np.array([]),\
                 hei=0.15,ylon=True,xon=True,lbar=True,flipy=False)
   
   Input:
      wks    -  Workstation ID
     data    -  2D matrix. Can be several matrices in a list
       vx    -  Latitude vector
       vy    -  y-vector. Can be several in a list
       
   Optional:
     xlab    -  Title for x-axis
     ylab    -  Title for y-axis
    vsurf    -  Vector of surface values to draw in
      hei    -  Height of plot(s)
     ylon    -  Turn on y labels on left side (else right)
      xon    -  Turn on x labels on bottom
     lbar    -  Turn on colorbar
   
   Output:
      None
      
   """
   ##
   res = Ngl.Resources()
   res.wkColorMap = 'ViBlGrWhYeOrRe'
   Ngl.set_values(wks,res)
   
   print '  Plotting overturning stream functions in (y,r) coordinates'
   print lbar
   if ( isinstance(data,list) ):
      nplots = len(data)
   else:
      nplots = 1
      data = [data]
   
   vy = fill_blanks(vy,nplots)
   ylab = fill_blanks(ylab,nplots)
   vsurf = fill_blanks(vsurf,nplots)
   ylon = fill_blanks(ylon,nplots)
   xon = fill_blanks(xon,nplots)
   lbar = fill_blanks(lbar,nplots)
   lbar[0] = True
   flipy = fill_blanks(flipy,nplots)
   
   hei = max([0.8/(nplots+1),hei])
   wth = min([0.7,hei * 4])
   vpy = 0.9 - hei * np.arange(0,nplots+1)
   
   ##
   ## Color levels for y-r stream functions
   ##
   colour_levels = np.arange(-190,210,20)
   
   for jn in range(0,nplots):
      
      zplot = data[jn]
      
      res = Ngl.Resources()
      
      res.nglMaximize                      =  False
      res.nglPaperOrientation              =  'Portrait'
      res.nglFrame                         =  False
      res.nglDraw                          =  False
      
      res.cnFillOn                         =  True
      res.cnLinesOn                        =  True
      res.cnLineLabelsOn                   =  False
      res.cnLineLabelDensityF              =  2
      res.cnLineLabelBackgroundColor       =  -1
      res.cnLevelSelectionMode             =  'ExplicitLevels'
      res.cnLevels                         =  colour_levels
      
      res.sfXArray                         =  vx
      res.sfYArray                         =  vy[jn]
      res.vpXF                             =  vpx
      res.vpWidthF                         =  wth
      res.vpYF                             =  vpy[jn]
      res.vpHeightF                        =  hei
      
      ##
      ## Axis
      ##
      res.tiYAxisFontHeightF               =  0.012
      res.tiYAxisString                    =  ylab[jn]
      res.tiXAxisString                    =  xlab
      
      if( ylon[jn] == True ):
         res.tiYAxisSide                   =  'Left'
         res.tmYLLabelsOn                  =  True
         res.tmYRLabelsOn                  =  False
         res.tmYLLabelFontHeightF          =  0.012
      else:
         res.tiYAxisSide                   =  'Right'
         res.tmYLLabelsOn                  =  False
         res.tmYRLabelsOn                  =  True
         res.tmYRLabelFontHeightF          =  0.012
      
      if( xon[jn] == True ):
         res.tiXAxisOn                     =  True
         res.tmXBLabelsOn                  =  True
         res.tiXAxisFontHeightF            =  0.012
         res.tmXBLabelFontHeightF          =  0.012
      else:
         res.tiXAxisOn                     =  False
         res.tmXBLabelsOn                  =  False
      
      ##
      ## Labelbar
      ##
      if( lbar[jn] == True ):
         res.lbTitleString         =  'Sverdrup (10~S~9~N~kg/s)'
         res.lbLabelFontHeightF    =  0.012
         res.lbTitleFontHeightF    =  0.015
         res.lbLabelBarOn          =  True
         res.lbOrientation         =  'Horizontal'
         
         res.pmLabelBarSide        =  'Top'
         res.pmLabelBarDisplayMode =  'Always'
         res.pmLabelBarWidthF      =  0.65
         res.pmLabelBarHeightF     =  0.07
      else:
         res.lbLabelBarOn            =  False
      
      ##
      ## Flip y axis?
      ##
      if( flipy[jn] == True ):
         res.trYReverse                    =  True
      else:
         res.trYReverse                    =  False
      
      
      ## Smooth
      if (lsmooth==True):
         sigma = 2
         order = 0
         for ji in range(0,5):
            ndimage.filters.gaussian_filter(zplot[:,:],sigma,order=order,\
                                            output=zplot[:,:],\
                                            mode='reflect', cval=0.0)
      
      cont = Ngl.contour(wks,zplot,res)
      
      ##
      ## Also draw the surface values
      ##
      if (vsurf[jn].shape[0] == vx.shape[0]):
         lres = Ngl.Resources()
         lres.gsLineThicknessF = 1.5
         lres.gsLineColor = 'black'
         lres.gsLineDashPattern = 1
         line = Ngl.add_polyline(wks,cont,vx,vsurf[jn],lres)
      else:
         print ' Length of vx and vsurf do not agree ' 
      
      ## And show the max/min values
      zmax = np.max( zplot.flatten() )
      zmin = np.min( zplot.flatten() )
      max_point = np.where(zplot == zmax)
      min_point = np.where(zplot == zmin)
      
      lmax = vx[max_point[1]][0]
      ymax = vy[jn][max_point[0]][0]
      print ' psimax = '+repr(zmax)
      print ' at lat = '+repr(lmax)+', y = '+repr(ymax)
      
      lmin = vx[min_point[1]][0]
      ymin = vy[jn][min_point[0]][0]
      print ' psimin = '+repr(zmin)
      print ' at lat = '+repr(lmin)+', y = '+repr(ymin)
      
      pres = Ngl.Resources()
      pres.gsMarkerColor = 'black'
      pres.gsMarkerThicknessF = 3.
      mark = Ngl.add_polymarker(wks,cont,lmax,ymax,pres)
      mark = Ngl.add_polymarker(wks,cont,lmin,ymin,pres)
      
      Ngl.draw(cont)
   
   #Ngl.frame(wks)
   
   flux_label = ['LH flux [PW]',\
                'DSE flux [PW]',\
                'MSE flux [PW]',\
                'Volume flux [m3/s]',
                'Pressure flux [hPa]',\
                'Sensible heat flux [PW]']
   
   jj = 0
   if(1):
      
      vy2 = np.zeros((nplots,vx.shape[0]))
      for jc in range(0,nplots):
         zplot = data[jc][:,:]
         chi = 0.5 * (vy[jc][1:] + vy[jc][:-1])
         for jj in range(0,vx.shape[0]):
            dpsi = zplot[1:,jj] - zplot[:-1,jj]
            vy2[jc,jj] = np.sum(dpsi * chi)
      
      vy2 = 10**(-3) * (-1) * vy2[:,:] # W->PW and change sign
      
      linecolors = ['blue','red','black','green','yellow','purple']
      
      del res
      res = Ngl.Resources()
      
      res.nglMaximize                      =  False
      res.nglPaperOrientation              =  'Portrait'
      res.nglFrame                         =  False
      res.nglDraw                          =  True
      
      res.xyLineColors                     =  linecolors
      #res.xyLineThicknesses                = [2,2,2]
      #res.xyLabelMode                      = 'Custom'
      #res.xyExplicitLabels                 = ['LH','DSE','MSE']
      #
      #if( np.mod(jc,2) == 0):
      #   res.tiYAxisSide                   =  'Left'
      #   res.tmYLLabelsOn                  =  True
      #   res.tmYRLabelsOn                  =  False
      #else:
      #   res.tiYAxisSide                   =  'Right'
      #   res.tmYLLabelsOn                  =  False
      #   res.tmYRLabelsOn                  =  True
      # 
      #if( jc == icoord-1):
      #   res.tiXAxisOn                     =  True
      #   res.tmXBLabelsOn                  =  True
      #else:
      #   res.tiXAxisOn                     =  False
      #   res.tmXBLabelsOn                  =  False
      
      ## Axis
      res.tiXAxisString                    =  'Latitude'
      res.tiYAxisString                    =  '[PW]'
      res.tiXAxisFontHeightF               =  0.012
      res.tiYAxisFontHeightF               =  0.012
      res.tmXBLabelFontHeightF             =  0.012
      res.tmYLLabelFontHeightF             =  0.012            
      res.trYMaxF                          =  6.
      res.trYMinF                          =  -6.
      
      res.vpXF                             =  vpx
      res.vpWidthF                         =  wth
      res.vpYF                             =  vpy[-1]
      res.vpHeightF                        =  hei
      
      cont = Ngl.xy(wks,vx,vy2[0:3],res)
      
      
   Ngl.frame(wks)
Exemple #12
0
#
#  Transpose the array so we can plot it, because Natgrid returns it
#  as an X x Y array, rather than Y x X which PyNGL expects.
#
zt = numpy.transpose(zo)

contour = Ngl.contour(wks, zt, resources)

#
# Add some polymarkers showing the original locations of the X,Y points.
#
poly_res = Ngl.Resources()
poly_res.gsMarkerIndex = 16
poly_res.gsMarkerSizeF = 0.015
Ngl.add_polymarker(wks, contour, x, y, poly_res)

Ngl.draw(contour)
Ngl.frame(wks)

#
# Now turn on RasterFill for the contours and compare.
#
resources.tiMainString = "Interpolation to a 2D grid (RasterFill)"
resources.cnFillMode = 'RasterFill'
contour = Ngl.contour(wks, zt, resources)

#
#  Draw polymarkers again.
#
Ngl.add_polymarker(wks, contour, x, y, poly_res)