Esempio n. 1
0
File: core.py Progetto: yyr/wrfout
    def draw_2d(self, varname, v):
        res = Ngl.Resources()
        plot_name = "wo_%s" % varname.lower()
        lgr.info("plot name set to - %s" % plot_name)
        wks = _get_wks(plot_name)
        for t in range(3):
            plot = Ngl.contour(wks, v[t, :, :], res)

        return plot
Esempio n. 2
0
    def draw_2d(self, varname, v):
        res = Ngl.Resources()
        plot_name = 'wo_%s' % varname.lower()
        lgr.info('plot name set to - %s' % plot_name)
        wks = _get_wks(plot_name)
        for t in range(3):
            plot = Ngl.contour(wks, v[t, :, :], res)

        return plot
Esempio n. 3
0
def print_cape_for_timestamp(wrf_data, timestamp, filepath):
    slp = pressure_lib.get_sea_level_pressure(wrf_data)
    cinfo = getvar(wrf_data, "cape_2d", missing=0.0)
    cape = cinfo[0, :, :].fillna(0)

    lat, lon = latlon_coords(slp)
    lat_normal = to_np(lat)
    lon_normal = to_np(lon)

    # rain sum
    cape_res = get_pyngl(cinfo)
    cape_res.nglDraw = False  # don't draw plot
    cape_res.nglFrame = False  # don't advance frame

    cape_res.cnFillOn = True  # turn on contour fill
    cape_res.cnLinesOn = False  # turn off contour lines
    cape_res.cnLineLabelsOn = False  # turn off line labels
    cape_res.cnFillMode = "RasterFill"  # These two resources
    cape_res.cnLevelSelectionMode = "ExplicitLevels"
    cape_res.cnFillColors        = numpy.array([ [255,255,255], [  0,255,  0], [  0,128,  0], \
                                                 [240,230,140], [255,255,  0], [255,140,  0], \
                                                 [255,  0,  0], [139,  0,  0], [186, 85,211],\
                                                 [153, 50,204], [139,  0,139], ],'f') / 255.
    cape_res.cnLevels = numpy.array(
        [.1, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500])

    cape_res = geography_lib.initialize_geography(cape_res, "gray50")

    cape_res.lbTitleString = "Convective available potential energy [CAPE] in (J/kg)"
    cape_res.lbOrientation = "horizontal"
    cape_res.lbTitleFontHeightF = 0.015
    cape_res.lbLabelFontHeightF = 0.015

    cape_res.tiMainString = "Thunderstorm probability (%s)" % timestamp.strftime(
        "%b %d %Y %HUTC")
    cape_res.trGridType = "TriangularMesh"  # can speed up plotting.
    cape_res.tfDoNDCOverlay = True  # required for native projection

    # pressure
    p_res = pressure_lib.get_pressure_resource(lat_normal, lon_normal)

    wk_res = Ngl.Resources()
    wk_res.wkWidth = 2500
    wk_res.wkHeight = 2500
    output_path = "%scape_%s" % (filepath, timestamp.strftime("%Y_%m_%d_%H"))
    wks_comp = Ngl.open_wks("png", output_path, wk_res)

    # creating plots for the measurands
    capeplot = Ngl.contour_map(wks_comp, cape, cape_res)
    pplot = Ngl.contour(wks_comp, slp, p_res)

    Ngl.overlay(capeplot, pplot)
    Ngl.maximize_plot(wks_comp, capeplot)
    Ngl.draw(capeplot)
    Ngl.frame(wks_comp)
    Ngl.delete_wks(wks_comp)  # delete currently used workstation
Esempio n. 4
0
def contour(A, **kwargs):
    #The following allows an expert user to pass
    #Ngl options directly to the plotter.
    #ToDo: Note that
    #options explicitly specified later will over-ride
    #what the user specified. This should be fixed,
    #by checking for things already specified. We should
    #also allow for using this resource to specify a color
    #map.
    if 'resource' in kwargs.keys():
        r = kwargs['resource']
    else:
        r = Dummy()
    #
    r.cnFillOn = True  #Uses color fill
    # Set axes if they have been specified
    # as keyword arguments
    if 'x' in kwargs.keys():
        r.sfXArray = kwargs['x']
    if 'y' in kwargs.keys():
        r.sfYArray = kwargs['y']
    #
    # Now create the plot

    rw = Dummy()
    #Set the color map
    if 'colors' in kwargs.keys():
        if (kwargs['colors'] == 'gray') or (kwargs['colors'] == 'grey'):
            #Set the default greyscale
            rw.wkColorMap = 'gsdtol'
        else:
            rw.wkColorMap = kwargs['colors']
    else:
        #Default rainbow color table
        rw.wkColorMap = "temp1"

    w = Ngl.open_wks('x11', 'Climate Workbook', rw)
    r.nglDraw = False
    r.nglFrame = False
    plot = Ngl.contour(w, A, r)
    #Now draw the plot
    r.nglDraw = True
    Ngl.panel(w, [plot], [1, 1], r)
    return plotObj(w, plot, rw)  #So user can delete or save plot
def contour(A,**kwargs):
    #The following allows an expert user to pass
    #Ngl options directly to the plotter.
    #ToDo: Note that
    #options explicitly specified later will over-ride
    #what the user specified. This should be fixed,
    #by checking for things already specified. We should
    #also allow for using this resource to specify a color
    #map.
    if 'resource' in kwargs.keys():
        r = kwargs['resource']
    else:
        r = Dummy()
    #
    r.cnFillOn = True #Uses color fill
    # Set axes if they have been specified
    # as keyword arguments
    if 'x' in kwargs.keys():
        r.sfXArray = kwargs['x']
    if 'y' in kwargs.keys():
        r.sfYArray = kwargs['y']
    #
    # Now create the plot
    
    rw = Dummy()
    #Set the color map
    if 'colors' in kwargs.keys():
        if (kwargs['colors'] == 'gray') or (kwargs['colors'] == 'grey') :
            #Set the default greyscale
            rw.wkColorMap = 'gsdtol'
        else:
            rw.wkColorMap = kwargs['colors']
    else:
        #Default rainbow color table
        rw.wkColorMap = "temp1" 
    
    w = Ngl.open_wks('x11','Climate Workbook',rw)
    r.nglDraw = False
    r.nglFrame = False
    plot = Ngl.contour(w,A,r)
    #Now draw the plot
    r.nglDraw = True
    Ngl.panel(w,[plot],[1,1],r)
    return plotObj(w,plot,rw) #So user can delete or save plot
Esempio n. 6
0
def get_3h_rainsum(previous_data, current_data, timestamp, filepath):
    slp = pressure_lib.get_sea_level_pressure(current_data)
    previous_sum, rain_con = get_cumulated_rain_sum(previous_data)
    current_sum, rain_con = get_cumulated_rain_sum(current_data)
    rain_sum = current_sum - previous_sum

    lat, lon = latlon_coords(rain_con)
    lat_normal = to_np(lat)
    lon_normal = to_np(lon)

    # rain sum
    rr_res = initialize_rain_resource(rain_con)

    rr_res.lbTitleString = "3h rainsum in (mm)"
    rr_res.lbOrientation = "horizontal"
    rr_res.lbTitleFontHeightF = 0.015
    rr_res.lbLabelFontHeightF = 0.015

    rr_res.tiMainString = "3h rainsum (%s)" % timestamp.strftime(
        "%b %d %Y %HUTC")
    rr_res.trGridType = "TriangularMesh"  # can speed up plotting.
    rr_res.tfDoNDCOverlay = True  # required for native projection

    # pressure
    p_res = pressure_lib.get_pressure_resource(lat_normal, lon_normal)

    wk_res = Ngl.Resources()
    wk_res.wkWidth = 2500
    wk_res.wkHeight = 2500
    output_path = "%srain_3h_%s" % (filepath,
                                    timestamp.strftime("%Y_%m_%d_%H"))
    wks_comp = Ngl.open_wks("png", output_path, wk_res)

    # creating plots for the measurands
    rrplot = Ngl.contour_map(wks_comp, rain_sum, rr_res)
    pplot = Ngl.contour(wks_comp, slp, p_res)

    Ngl.overlay(rrplot, pplot)
    Ngl.maximize_plot(wks_comp, rrplot)
    Ngl.draw(rrplot)
    Ngl.frame(wks_comp)
    Ngl.delete_wks(wks_comp)  # delete currently used workstation
Esempio n. 7
0
bres.sfYArray = lat[:]

base_plot = Ngl.contour_map(wks, unew, bres)

# Set resources for contour plot only
ores = set_common_resources()

ores.cnFillOpacityF = 1.0  # Fully opaque
ores.lbLabelBarOn = False  # Turn off labelbar
ores.sfMissingValueV = u._FillValue

ores.sfXArray = lon['lon|-120:120']
ores.sfYArray = lat['lat|-30:30']

# Use PyNIO's selection syntax to subset the lat/lon area of interest
overlay_plot = Ngl.contour(wks, u['time|i1 lat|-30:30 lon|-120:120'], ores)

# Overlay the contour plot on the contour/map plot
Ngl.overlay(base_plot, overlay_plot)

# Drawing the base plot draws both plots
Ngl.draw(base_plot)
Ngl.frame(wks)

# Create the contour/plot again, but with no transparency
del bres.cnFillOpacityF
plot = Ngl.contour_map(wks, u[1, :, :], bres)

# Set resources for a partially transparent polygon.
gnres = Ngl.Resources()
gnres.gsFillOpacityF = 0.6  # mostly opaque
Esempio n. 8
0
    res.cnLineLabelsOn = True
    res.cnLinesOn = True
    res.cnMonoLineLabelFontColor = True
    res.lbLabelFontHeightF = 0.01
    res.cnLineDashPattern = 0
    res.cnLineThicknessF = 5.0
    res.cnLineColor = "steelblue1"

    res.cnLevelSelectionMode = "ManualLevels"
    res.cnMinLevelValF = -85.0
    res.cnMaxLevelValF = 115.0
    res.cnLevelSpacingF = 100.0

    # plot ITD and overlay on colour contours

    ws_plot2 = ngl.contour(wks, ws, res)

    ngl.overlay(ws_plot, ws_plot2)

ngl.overlay(ws_plot, uv_plot)
ngl.maximize_plot(wks, ws_plot)
ngl.draw(ws_plot)
ngl.frame(wks)

ngl.destroy(wks)
del res
del vcres

###################################################################################################

# open forecast file
def plot_psirr(vpx=0.2, vpy=0.8, hei=0.4, lbar=True, xlab=1,ylab=1):
   
   ##
   ## Colors for hydrothermal stream functions
   ##
   ld   = 550.
   dl   = 50
   
   res = Ngl.Resources()
   res.wkColorMap = 'WhiteBlue'
   #res.wkColorMap = 'BlueWhiteOrangeRed'
   Ngl.set_values(wks,res)
   
   ##
   ## Reverse colormap
   ##
   del res
   res = Ngl.Resources()
   cmap = Ngl.retrieve_colormap(wks)
   cmap[2:,:] = cmap[-1:1:-1,:]
   res.wkColorMap = cmap
   Ngl.set_values(wks,res)
         
   psi_levels = np.arange(-ld,0.,dl)
   
   if(1):
      
      if(1):
         
         
         del res
         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                         =  psi_levels
         
         if (lbar):
            res.pmLabelBarSide                   =  'Top'
            res.lbLabelBarOn                     =  True
            res.lbOrientation                    =  'Horizontal'
            res.pmLabelBarDisplayMode            =  'Always'
            res.pmLabelBarWidthF                 =  0.6
            res.pmLabelBarHeightF                =  0.03
            res.pmLabelBarOrthogonalPosF         =  0.07
            #res.pmLabelBarParallelPosF           =  1.1
            res.lbTitleString                    =  'Sv (10~S~9~N~kg/s)'
            res.lbLabelFontHeightF               =  0.012
            res.lbTitleFontHeightF               =  0.015
         else:
            res.pmLabelBarDisplayMode            =  'Never'
         
         res.sfXArray                         =  vx
         res.sfYArray                         =  vy
         
         res.trXMinF                          =  -3
         res.trXMaxF                          =  55
         res.trYMinF                          =  250
         res.trYMaxF                          =  360
         
         res.tiXAxisString                    =  'Latent heat [kJ/kg]'
         res.tiYAxisString                    =  'Dry static energy [kJ/kg]'
         res.tiMainString                     =  title
         res.tiMainOffsetYF                   =  -0.045
         res.tiMainFontHeightF                =  0.015
         
         if (xlab == 1):
            res.tiXAxisOn                     =  True
            res.tmXBLabelsOn                  =  True
            res.tiXAxisSide                   =  'Bottom'
         elif (xlab == -1):
            res.tiXAxisOn                      =  True
            res.tmXBLabelsOn                  =  False
            res.tmXTLabelsOn                  =  True
            res.tiXAxisSide                   =  'Top'
         elif (xlab == 0):
            res.tiXAxisOn                     =  False
            res.tmXBLabelsOn                  =  False
            res.tmXTLabelsOn                  =  False
            
         if (ylab == 1):
            res.tiYAxisOn                     =  True
            res.tmYLLabelsOn                  =  True
            res.tmYRLabelsOn                  =  False
            res.tiYAxisSide                   =  'Left'
         elif (ylab == -1):
            res.tiYAxisOn                     =  True
            res.tmYLLabelsOn                  =  False
            res.tmYRLabelsOn                  =  True
            res.tiYAxisSide                   =  'Right'
         elif (ylab == 0):
            res.tiYAxisOn                     =  False
            res.tmYLLabelsOn                  =  False
            res.tmYRLabelsOn                  =  False
            
         res.vpWidthF                         =  hei
         res.vpHeightF                        =  hei
         
         res.vpYF                             =  vpy
         res.vpXF                             =  vpx
         
         lsmooth = False
         if (lsmooth):
            sigma = 2
            order = 0
            for ji in range(0,2):
               ndimage.filters.gaussian_filter(zplot[:,:],sigma,order=order,\
                                               output=zplot[:,:],\
                                               mode='reflect', cval=0.0)
         
         cont = Ngl.contour(wks,zplot[:,:],res)
         
         ## Clausius-Clapeyron line
         vy_cc = np.linspace(240,360,101)
         press = 101300.
         vx_cc,es = cclap(vy_cc*1000/1004.,press)
         vx_cc = 2.5 * 10**3 * vx_cc
         #ccstring = 'C-C, RH=100%'
         lres = Ngl.Resources()
         lres.gsLineDashPattern         =  15  
         lres.gsLineLabelFontHeightF    =  0.009
         lres.gsLineThicknessF          =  2
         #lres.gsLineLabelString         =  ccstring
         line = Ngl.add_polyline(wks,cont,vx_cc,vy_cc,lres)
         
         ## MSE profile
         lres = Ngl.Resources()
         lres.gsLineDashPattern         =  1
         lres.gsLineThicknessF          =  3  
         line = Ngl.add_polyline(wks,cont,vlh,vdse,lres)
         
         Ngl.draw(cont)
Esempio n. 10
0
File: cn12p.py Progetto: yyr/pyngl
mpres.mpMaskAreaSpecifiers  =  mask_specs      # areas to mask (protect)

#
# This set of resources deals with a map labelbar.
#
# Note that this is different from a contour labelbar
# (which we will turn off below), and we have more 
# control over it (i.e. we can set the number of boxes,
# the fill # colors, etc) than we do with a contour labelbar.
#
mpres.pmLabelBarDisplayMode =  "Always"        # Turn on a map labelbar

# Labelbar resources.
mpres.lbLabelStrings        = ["Ocean","Land","< 0","0-10","10-20","20-30",\
                               "30-40","40-50","50-60","60-70","70-80",    \
                               "80-90","90-100","> 100"]
mpres.lbFillColors          = mp_fill_colrs + cn_fill_clrs

# Fill resources
cnres.cnFillColors          =  cn_fill_clrs
cnres.pmLabelBarDisplayMode = "Never"  # turn off, b/c map has one turned on

contour = Ngl.contour(wks,z[:,:],cnres)
map     = Ngl.map(wks,mpres)

Ngl.overlay(map,contour)
Ngl.draw(map)
Ngl.frame(wks)

Ngl.end()
Esempio n. 11
0
    T[i, :] = (jspn + ispn[i]).astype('f')

T = 100.0 - numpy.sqrt(64 * T)

#
# Open the workstation and change the color map.
#
rlist = Ngl.Resources()
rlist.wkColorMap = "default"
wks_type = "png"

wks = Ngl.open_wks(wks_type, "contour2", rlist)

cnres = Ngl.Resources()
cnres.cnFillOn = True  # Turn on contour level fill.
cnres.cnMonoFillPattern = False  # Indicate you want multiple fill patterns.

#
# Set cnFillPatterns and cnFillColors to various indexes representing
# fill patterns and colors.  A fill pattern index of "0" is solid fill.
# If you don't want any fill for a particular contour level, set it
# to "-1," which means "transparent."
#
cnres.cnFillPatterns = [0, 0, 0, 2, 3, 6, 8, 10, -1, 9, 11, 12, 17, 16]
cnres.cnMonoFillScale = False  # We want to use multiple fill scales.
cnres.cnFillScales = [1., .5, .6, 1., .7, .5, .4, .9, .6, 1., 1., .8, .5, .9]
cnres.cnFillColors = [6, 8, 20, 22, 4, 2, 10, 1, 12, 15, 1, 13, 5, 7]

contour = Ngl.contour(wks, T, cnres)
Ngl.end()
Esempio n. 12
0
resources.cnFillOn          = True
resources.cnFillMode        = "RasterFill"
resources.cnLinesOn         = False
resources.cnLineLabelsOn    = False
resources.cnMaxLevelCount   = 22

resources.tiMainString      = "2562 Element Geodesic grid"

resources.lbBoxLinesOn      = False
resources.lbTitleString     = "kinetic energy"

resources.nglDraw           = False   # Just create the plot. Don't
resources.nglFrame          = False   # draw it or advance the frame.

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

#
# Retrieve the actual lat/lon end points of the scalar array so
# we know where to overlay on map.
#
xs = Ngl.get_float(contour.sffield,"sfXCActualStartF")
xe = Ngl.get_float(contour.sffield,"sfXCActualEndF")
ys = Ngl.get_float(contour.sffield,"sfYCActualStartF")
ye = Ngl.get_float(contour.sffield,"sfYCActualEndF")

resources.nglDraw           = True      # Now we want to draw the plot
resources.nglFrame          = True      # and advance the frame.

resources.mpGridAndLimbOn   = False
resources.mpProjection      = "Orthographic"
Esempio n. 13
0
resources.tiMainString = "Depth of a subsurface stratum"
resources.tiMainFont = "Times-Bold"
resources.tiXAxisString = "x values"  # X axis label.
resources.tiYAxisString = "y values"  # Y axis label.

resources.cnFillOn = True  # Turn on contour fill.
resources.cnFillPalette = cmap  # Set colors for contours.
resources.cnInfoLabelOn = False  # Turn off info label.
resources.cnLineLabelsOn = False  # Turn off line labels.

resources.lbOrientation = "Horizontal"  # Draw it horizontally.
# label bar.
resources.vpYF = 0.9  # Change Y location of plot.

zt = numpy.transpose(zo)
contour = Ngl.contour(xwks, zt, resources)

#----------- Begin second plot -----------------------------------------

del resources
resources = Ngl.Resources()
resources.tiMainString = "~F26~slices"  # Define a title.

resources.xyLineColors = ["red", "cyan", "darkgreen", "darkorchid4"]
resources.xyLineThicknessF = 3.0  # Define line thickness.

resources.pmLegendDisplayMode = "Always"  # Turn on the drawing
resources.pmLegendZone = 0  # Change the location
resources.pmLegendOrthogonalPosF = 0.31  # of the legend
resources.lgJustification = "BottomRight"
resources.pmLegendWidthF = 0.4  # Change width and
Esempio n. 14
0
#
resources = Ngl.Resources()

resources.sfXArray        = lat_t
resources.sfYArray        = z_t
resources.sfMissingValueV = T._FillValue[0]

resources.cnFillOn        = True
resources.cnLineLabelsOn  = False

resources.tiMainString    = "Default axes"        # main title

#
# Draw the plot as is, with no transformations in place.
#
plot = Ngl.contour(wks,T,resources)

#
# Linearize the Y axis.
#
resources.tiMainString = "Y axis linearized"
resources.nglYAxisType = "LinearAxis"
plot = Ngl.contour(wks,T,resources)

#
# Linearize the X axis.
#
resources.tiMainString = "X and Y axes linearized"
resources.nglXAxisType = "LinearAxis"
plot = Ngl.contour(wks,T,resources)
Esempio n. 15
0
res.cnLineLabelsOn        =  False        #-- turn off line labels.
res.cnInfoLabelOn         =  False        #-- turn off info label.
res.cnFillPalette         = "BlueWhiteOrangeRed" #-- set color map.
res.pmLabelBarOrthogonalPosF = -0.03      #-- move labelbar close to plot

res.sfXArray              =  lon          #-- scalar field x
res.sfYArray              =  lev          #-- scalar field y

res.trYReverse            = True          #-- reverse the Y axis
res.nglYAxisType          = "LogAxis"     #-- y axis log

res.tiYAxisString         = "%s (hPa)" % f.variables["lev"].long_name

res.nglPointTickmarksOutward = True       #-- point tickmarks out

res.tmYLMode              = "Explicit"    #-- set y axis tickmark labels
res.tmXBMode              = "Explicit"    #-- set x axis tickmark labels
res.tmYLValues            = levs
res.tmXBValues            = lons
res.tmYLLabels            = map(str,levs)
res.tmXBLabels            = nice_lon_labels(lons)

res.tmXBLabelFontHeightF  = 0.015        # - make font smaller
res.tmYLLabelFontHeightF  = 0.015

map = Ngl.contour(wks,t26,res)            #-- draw contours 

#-- end
Ngl.end()

Esempio n. 16
0
tempsfc_res.tmYLLabelFont  = 26            # Change the font.
tempsfc_res.tmXBValues     = taus
tempsfc_res.tmXBLabels     = taus
tempsfc_res.tmXTOn         = False         # turn off the top tickmarks
tempsfc_res.xyLineThicknesses = 2
tempsfc_res.xyLineColor    =  "red"

tempsfc_res.nglDraw         = False     # Don't draw individual plot.
tempsfc_res.nglFrame        = False     # Don't advance frame.
tempsfc_res.nglMaximize     = False    # Do not maximize plot in frame 

#
#  Create the four plots (they won't get drawn here, because nglDraw
#  was set to False for all three of them.
#
rhfill    = Ngl.contour(wks,smothrh,rh_res)
templine  = Ngl.contour(wks,smothtemp,temp_res)
windlayer = Ngl.vector(wks,ugrid,vgrid,uv_res)
rainhist  = Ngl.xy(wks,taus,rain03,rain_res)

#
# For the rain plot, we want filled bars instead of a curve, so create
# a dummy plot with all the Y values equal to rain_res.trYMinF. This
# will insure no curve gets drawn. Then, add the bars and bar outlines
# later with Ngl.add_polygon and Ngl.add_polyline.
#
#
# Make dummy data equal to min Y axis value.
#
dummy = rain_res.trYMinF * Numeric.ones([len(rain03)],rain03.typecode())
Esempio n. 17
0
resources = Ngl.Resources()
#
#  Define a NumPy data array containing the temperature for the
#  first time step and first level. This array does not have the
#  attributes that are associated with the variable temp.
#
tempa = temp[0, 0, :, :]
tempa = tempa - 273.15

#
#  Specify the main title base on the long_name attribute of temp.
#
if hasattr(temp, "long_name"):
    resources.tiMainString = temp.long_name

plot = Ngl.contour(wks, tempa, resources)

# ----------- Begin second plot -----------------------------------------

resources.cnMonoLineColor = False  # Allow multiple colors for contour lines.
resources.tiMainString = "Temperature (C)"

plot = Ngl.contour(wks, tempa, resources)  # Draw a contour plot.

# ----------- Begin third plot -----------------------------------------

resources.cnFillOn = True  # Turn on contour line fill.
resources.cnMonoFillPattern = False  # Turn off using a single fill pattern.
resources.cnMonoFillColor = True
resources.cnMonoLineColor = True
def plot_psirr(wks, zplot, vx, vy, xlab = 'x', ylab = 'y', vpx=0.2, vpy=0.8, \
               hei=0.4, cc='dse',lsmooth=False, frame=True):
   """
   """
   
   
   ##
   ## Colors for hydrothermal stream functions
   ##
   ld   = 450.
   dl   = 60
   
   res = Ngl.Resources()
   res.wkColorMap = 'WhiteBlue'
   #res.wkColorMap = 'BlueWhiteOrangeRed'
   Ngl.set_values(wks,res)
   
   ##
   ## Reverse colormap
   ##
   del res
   res = Ngl.Resources()
   cmap = Ngl.retrieve_colormap(wks)
   cmap[2:,:] = cmap[-1:1:-1,:]
   res.wkColorMap = cmap
   Ngl.set_values(wks,res)
         
   psi_levels = np.arange(-ld,0.,dl)
   
   ##
   ## Positions of four subplots
   ##
   
   print '  Plotting stream functions in (r,r) coordinates'
   
   if(1):
      
      if(1):
         
         #vu = np.zeros(zplot[-1,:,:].shape)
         #vv = np.zeros(zplot[-1,:,:].shape)
         
         #vu[1:,:] = zplot[-1,0:-1,:] - zplot[-1,1:,:]
         #vv[:,1:] = zplot[-1,:,1:] - zplot[-1,:,0:-1]
               
         title = 'psi('+xlab+','+ylab+')'
                  
         print ' Amplitude, max. err : '+repr(np.max(np.abs(zplot[:,:]))),\
                                         repr(np.max(np.abs(zplot[:,-1])))
         
         del res
         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                         =  psi_levels
      
         res.pmLabelBarSide                   =  'Right'
         res.lbLabelBarOn                     =  True
         res.lbOrientation                    =  'Vertical'
         res.pmLabelBarDisplayMode            =  'Always'
         res.pmLabelBarWidthF                 =  0.03
         res.pmLabelBarHeightF                =  hei
         res.lbTitleString                    =  'Sv (10~S~9~N~kg/s)'
         res.lbLabelFontHeightF               =  0.01
         res.lbTitleFontHeightF               =  0.01
         
         res.sfXArray                         =  vx
         res.sfYArray                         =  vy
         
         res.tiXAxisString                    =  xlab
         res.tiYAxisString                    =  ylab
         
         res.vpWidthF                         =  hei
         res.vpHeightF                        =  hei
         
         res.vpYF                             =  vpy
         res.vpXF                             =  vpx
         
         if (lsmooth):
            sigma = 2
            order = 0
            for ji in range(0,2):
               ndimage.filters.gaussian_filter(zplot[:,:],sigma,order=order,\
                                               output=zplot[:,:],\
                                               mode='reflect', cval=0.0)
         
         cont = Ngl.contour(wks,zplot[:,:],res)
         
         wks,cont = plot_cc(wks,cont,x='lh',y=cc)
         Ngl.draw(cont)
         
         if(frame):
            Ngl.frame(wks)
Esempio n. 19
0
  T[i,:] = (jspn + ispn[i]).astype('f')

T = 100.0 - numpy.sqrt(64 * T)

#
# Open the workstation and change the color map.
#
rlist    = Ngl.Resources()
rlist.wkColorMap = "default"
wks_type = "ps"

wks = Ngl.open_wks(wks_type,"contour2",rlist)

cnres                   = Ngl.Resources()
cnres.cnFillOn          = True   # Turn on contour level fill.
cnres.cnMonoFillPattern = False  # Indicate you want multiple fill patterns.

#
# Set cnFillPatterns and cnFillColors to various indexes representing
# fill patterns and colors.  A fill pattern index of "0" is solid fill.
# If you don't want any fill for a particular contour level, set it
# to "-1," which means "transparent."
#
cnres.cnFillPatterns    = [0, 0, 0, 2, 3, 6, 8,10,-1, 9, 11,12,17,16]
cnres.cnMonoFillScale   = False    # We want to use multiple fill scales.
cnres.cnFillScales      = [1.,.5,.6,1.,.7,.5,.4,.9,.6,1.,1.,.8,.5,.9]
cnres.cnFillColors      = [ 6, 8,20,22, 4, 2,10, 1,12,15, 1,13, 5, 7]
  
contour = Ngl.contour(wks,T,cnres)
Ngl.end()
Esempio n. 20
0
cnres.nglDraw                  = False    # Turn off draw and frame.
cnres.nglFrame                 = False    # We will do this later.

cnres.sfXArray                 = lon
cnres.sfYArray                 = time

cnres.tmXBMode                 = "Explicit"    # Label X and Y axes
cnres.tmYLMode                 = "Explicit"    # with explicit labels.
cnres.tmXBValues               = lon_values
cnres.tmYLValues               = time_values
cnres.tmXBLabels               = lon_labels
cnres.tmYLLabels               = time_labels

cnres.nglPointTickmarksOutward = True

contour = Ngl.contour(wks,chi,cnres)  # Create, but don't draw contour plot.

neg_dash_contours(contour)           # Dash the negative contours.

Ngl.draw(contour)            # Now draw contours and
Ngl.frame(wks)               # advance the frame.

#
# Set some new resources to control how the lines are labeled.
# Use Ngl.set_values to apply these new resources to our existing
# plot.
#

nrlist                          = Ngl.Resources()

nrlist.cnLineLabelPlacementMode = "Computed"
Esempio n. 21
0
resources = Ngl.Resources()
#
#  Define a NumPy data array containing the temperature for the
#  first time step and first level. This array does not have the
#  attributes that are associated with the variable temp.
#
tempa = temp[0,0,:,:]
tempa = tempa - 273.15

#
#  Specify the main title base on the long_name attribute of temp.
#
if hasattr(temp,"long_name"):
  resources.tiMainString = temp.long_name

plot = Ngl.contour(wks,tempa,resources)

#----------- Begin second plot -----------------------------------------

resources.cnMonoLineColor = False  # Allow multiple colors for contour lines.
resources.tiMainString    = "Temperature (C)"

plot = Ngl.contour(wks,tempa,resources)  # Draw a contour plot.

#----------- Begin third plot -----------------------------------------

resources.cnFillOn          = True    # Turn on contour line fill.
resources.cnFillPalette     = "default"   #  Set colors for contours
resources.cnMonoFillPattern = False   # Turn off using a single fill pattern.
resources.cnMonoFillColor   = True
resources.cnMonoLineColor   = True
 #   res.tiYAxisSide             =  'Right'
 #   res.tmYLLabelsOn            =  False
 #   res.tmYRLabelsOn            =  True
 #   res.pmLabelBarDisplayMode   =  'Never'
 
 res.cnFillOn                   =  True
 res.cnLinesOn                  =  False
 res.cnLineLabelsOn             =  False
 res.cnLevels                   =  vol_levels
 res.vpXF                       =  0.55#vxf[ja]
 res.vpWidthF                   =  0.3
 res.vpYF                       =  0.7#vyf[ja]
 res.vpHeightF                  =  0.3
 #res.tiMainString               =  title[ja]
  
 volplot = Ngl.contour(wks,zplot[ja,:,:],res)
 
 ##
 ## Draw hydrothermal stream lines on top
 ##
 res.pmLabelBarDisplayMode      =  'Never'
 res.cnFillOn                   =  False
 res.cnLinesOn                  =  True
 res.cnLineLabelsOn             =  True
 res.cnInfoLabelOn              =  False
 res.cnLevels                   =  psi_levels
 
 psi2 = psi * 10**(-9)
 psiplot = Ngl.contour(wks,psi2,res)
 
 Ngl.overlay(volplot,psiplot)
Esempio n. 23
0
resources.sfXArray         = lons  # Portion of map on which to overlay
resources.sfYArray         = lats  # contour plot.
#resources.sfElementNodes   = ele
#resources.sfFirstNodeIndex = 1

resources.cnFillOn         = True
resources.cnLinesOn        = False
resources.cnLineLabelsOn   = False

#
# This plot isn't very interesting because it isn't overlaid on a map.
# We are only creating it so we can retrieve information that we need
# to overlay it on a map plot later. You can turn off this plot
# by setting the nglDraw and nglFrame resources to False.
#
contour = Ngl.contour(wks,to_plot,resources)

#
#  The next set of resources will apply to the map plot.
#
resources.mpProjection = "Stereographic"


#
# Once the high resolution coastline data files have been
# downloaded (see the Notes section above for details), to
# access them you need to change the following resource
# to "HighRes".
#
resources.mpDataBaseVersion = "MediumRes"
Esempio n. 24
0
                               "250","200","150","100", "50"]
resources.tmYLMinorOn   = False        # No minor tick marks.

resources.cnFillOn          = True  # Turn on contour level fill.
resources.cnMonoFillColor   = True  # Use one fill color.
resources.cnMonoFillPattern = False # Use multiple fill patterns.

resources.cnLineLabelAngleF = 0. # Draw contour line labels right-side up.
resources.cnLevelSpacingF   = 1.0

resources.nglDraw  = False  # Don't draw the plot or advance the
resources.nglFrame = False  # frame in the call to Ngl.contour.

resources.nglMaximize = False
resources.pmLabelBarDisplayMode = "Never"    # Turn off label bar.
contour = Ngl.contour(wks, unew, resources)  # Create a contour plot.

levels = Ngl.get_float_array(contour,"cnLevels")

patterns = numpy.zeros((len(levels)+1),'i')
patterns[:] = -1

for i in xrange(len(levels)):
  if (levels[i] <= -6.):
    patterns[i] = 5
  else:
    if (levels[i] > 0.):
      patterns[i] = 17.
patterns[-1]  = 17 # last pattern

rlist = Ngl.Resources()
Esempio n. 25
0
    # coordinate settings
    res.sfXArray = lon[it, 0:ncols[it]]
    res.sfYArray = lat[it, 0:ncols[it]]
    res.vpWidthF = 1
    res.vpHeightF = 0.5
    # Set resources necessary to get map projection correct.
    # res.mpCenterLonF       = 180 

    # label settings
    lon_values  = Ngl.fspan(np.min(lon), np.max(lon), 5)
    lon_labels  = ["0","90","180","270","360"]
    lat_values  = Ngl.fspan(np.min(lat), np.max(lat), 5)
    lat_labels = ["-90", "-45", "0", "45", "90"]
    res.tmXBMode                 = "Explicit"    # Label X and Y axes
    res.tmYLMode                 = "Explicit"    # with explicit labels.
    res.tmXBValues               = lon_values
    res.tmYLValues               = lat_values
    res.tmXBLabels               = lon_labels
    res.tmYLLabels               = lat_labels

    contour = Ngl.contour(wks,q[it, 0:ncols[it]],res)

    gsres                  = Ngl.Resources()
    gsres.gsLineColor      = "Gray25"
    gsres.gsLineThicknessF = 3.0
    # print(vertx[0, :, 0],verty[0, :, 0])    
    for nc in range(ncols[it]):
        Ngl.polyline(wks,contour,vertx[it, :, nc],verty[it, :, nc],gsres)    
    Ngl.frame(wks)
Ngl.end()
Esempio n. 26
0
resources.lbLabelFont = "Helvetica"
resources.lbLabelFontHeightF = 0.015
resources.lbBottomMarginF = 0.4  #  Move the label bar up.

resources.tmXBLabelFont = "Helvetica"
resources.tmXBLabelFontHeightF = 0.02
resources.tmYLLabelFont = "Helvetica"
resources.tmYLLabelFontHeightF = 0.02
# label bar.
resources.vpYF = 0.9  # Change Y location of plot.

#
#  Contour
#
zt = numpy.transpose(zo)
contour = Ngl.contour(wks, zt, resources)

#
#  Repeat the above, except disallow negative interpolated values.
#
Ngl.nnsetp("non", 1)
resources.tiMainString = "Negative interpolants not allowed"
zo = Ngl.natgrid(x, y, z, xo, yo)
zt = numpy.transpose(zo)
contour = Ngl.contour(wks, zt, resources)

#
#  Retrieve the default value for the tautness factor "bJ".
#
bJ_value = Ngl.nngetp("bJ")
# print(bJ_value)
Esempio n. 27
0
File: ngl08p.py Progetto: akrherz/me
resources.tiMainString          = "Depth of a subsurface stratum"
resources.tiMainFont            = "Times-Bold"
resources.tiXAxisString         = "x values"    # X axis label.
resources.tiYAxisString         = "y values"    # Y axis label.

resources.cnFillOn              = True     # Turn on contour fill.
resources.cnInfoLabelOn         = False    # Turn off info label.
resources.cnLineLabelsOn        = False    # Turn off line labels.

resources.lbOrientation         = "Horizontal" # Draw it horizontally.
                                                 # label bar.
resources.nglSpreadColors = False    # Do not interpolate color space.
resources.vpYF = 0.9   # Change Y location of plot.

zt = Numeric.transpose(zo)
contour = Ngl.contour(xwks,zt,resources) 

#----------- Begin second plot -----------------------------------------

del resources
resources = Ngl.Resources()
resources.tiMainString        = ":F26:slices"   # Define a title.

resources.xyLineColors        = [2,8,10,14]    # Define line colors.
resources.xyLineThicknessF    = 3.0             # Define line thickness.

resources.pmLegendDisplayMode    = "Always"     # Turn on the drawing
resources.pmLegendZone           = 0            # Change the location
resources.pmLegendOrthogonalPosF = 0.31         # of the legend
resources.lgJustification        = "BottomRight"
resources.pmLegendWidthF         = 0.4          # Change width and
Esempio n. 28
0
    res.cnLineLabelsOn = True
    res.cnLinesOn = True
    res.cnMonoLineLabelFontColor = True
    res.lbLabelFontHeightF = 0.01
    res.cnLineDashPattern = 11
    res.cnLineThicknessF = 5.0
    res.cnLineColor = "purple"

    res.cnLevelSelectionMode = "ManualLevels"
    res.cnMinLevelValF = -85.0
    res.cnMaxLevelValF = 115.0
    res.cnLevelSpacingF = 100.0

    # plot ITD and overlay on colour contours

    dp_plot2 = ngl.contour(wks, dewpoint, res)

    ngl.overlay(dp_plot, dp_plot2)

ngl.maximize_plot(wks, dp_plot)
ngl.draw(dp_plot)
ngl.frame(wks)

ngl.destroy(wks)
del res
del dewpoint

###################################################################################################

# open forecast file
Esempio n. 29
0
#
# Set some font heights to make them slightly bigger than the default.
# Turn off nglScale, because this resource wants to set the axes font
# heights for you.
#
resources.nglScale               = False
resources.cnLineLabelFontHeightF = 0.025
resources.tiMainFontHeightF      = 0.037
resources.lbLabelFontHeightF     = 0.032
resources.tmXBLabelFontHeightF   = 0.030
resources.tmYLLabelFontHeightF   = 0.030

for i in range(0,nplots):
  resources.tiMainString  = "Temperature at time = " + str(i)
  plot.append(Ngl.contour(wks,temp[i,:,:],resources))

Ngl.panel(wks,plot[0:4],[2,2])    # Draw 2 rows/2 columns of plots.

#
# Now add some extra white space around each plot.
#

panelres                            = Ngl.Resources()
panelres.nglPanelYWhiteSpacePercent = 5.
panelres.nglPanelXWhiteSpacePercent = 5.
Ngl.panel(wks,plot[0:4],[2,2],panelres)    # Draw 2 rows/2 columns of plots.

#
# This section will set resources for drawing contour plots over a map.
#
Esempio n. 30
0
File: ngl11p.py Progetto: yyr/pyngl
                               "250","200","150","100", "50"]
resources.tmYLMinorOn   = False        # No minor tick marks.

resources.cnFillOn          = True  # Turn on contour level fill.
resources.cnMonoFillColor   = True  # Use one fill color.
resources.cnMonoFillPattern = False # Use multiple fill patterns.

resources.cnLineLabelAngleF = 0. # Draw contour line labels right-side up.
resources.cnLevelSpacingF   = 1.0

resources.nglDraw  = False  # Don't draw the plot or advance the
resources.nglFrame = False  # frame in the call to Ngl.contour.

resources.nglMaximize = False
resources.pmLabelBarDisplayMode = "Never"    # Turn off label bar.
contour = Ngl.contour(wks, unew, resources)  # Create a contour plot.

levels = Ngl.get_float_array(contour,"cnLevels")

patterns = numpy.zeros((len(levels)+1),'i')
patterns[:] = -1

for i in xrange(len(levels)):
  if (levels[i] <= -6.):
    patterns[i] = 5
  else:
    if (levels[i] > 0.):
      patterns[i] = 17.
patterns[-1]  = 17 # last pattern

rlist = Ngl.Resources()
Esempio n. 31
0
mpres.mpInlandWaterFillColor = "transparent"
mpres.mpOceanFillColor = "transparent"
mpres.mpLandFillColor = "tan"
mpres.mpLabelsOn = False
mpres.mpLeftCornerLatF = 10.
mpres.mpLeftCornerLonF = -180.
mpres.mpLimitMode = "corners"
mpres.mpProjection = "Stereographic"
mpres.mpRightCornerLatF = 10.
mpres.mpRightCornerLonF = 0.

mpres.tiMainFontHeightF = 0.02
mpres.tiMainString = "Busy graphic with contours and streamlines"

stream = Ngl.streamline(wks, data[0, :, :], data[1, :, :], stres)
contour = Ngl.contour(wks, data[2, :, :], cnres)
map = Ngl.map(wks, mpres)

Ngl.overlay(map, stream)
Ngl.overlay(map, contour)

# Since we overlaid 2 plots, we need to resize them to make sure
# they fit in frame.
Ngl.maximize_plot(wks, map)

Ngl.draw(map)
Ngl.frame(wks)

del cnres.nglDraw
del cnres.nglFrame
del mpres.nglDraw
Esempio n. 32
0
def plot_Robinson_pyngl(var,
                        lon,
                        lat,
                        wks_name='plot',
                        clim=None,
                        cspace=None,
                        cmap=None):

    #
    #  Select a colormap and open a workstation.
    #
    rlist = Ngl.Resources()

    wks_type = "png"
    wks = Ngl.open_wks(wks_type, wks_name, rlist)

    if cmap is None:
        mycmap = 'BlAqGrYeOrReVi200'
        Ngl.define_colormap(wks, mycmap)
    else:
        try:
            mycmap = '/Users/frederic/python/cmap/' + cmap
            mycmap = np.loadtxt(mycmap)
        except:
            mycmap = cmap
        try:
            Ngl.define_colormap(wks, mycmap)
        except:
            raise Warning('Unknown colormap')

    #
    #  The next set of resources will apply to the contour plot and the labelbar.
    #
    resources = Ngl.Resources()

    resources.sfXArray = lon
    resources.sfYArray = lat

    resources.gsnMaximize = True  # use full page

    resources.cnFillOn = True
    resources.cnFillMode = "RasterFill"
    resources.cnMaxLevelCount = 255
    resources.cnLinesOn = False
    resources.cnLineLabelsOn = False
    if clim is not None:
        resources.cnLevelSelectionMode = "ManualLevels"  # set manual contour levels
        resources.cnMinLevelValF = clim[0]  # set min contour level
        resources.cnMaxLevelValF = clim[1]  # set max contour level
        if cspace is None:
            LevelSpacing = (clim[1] - clim[0]) / 100.
            resources.cnLevelSpacingF = LevelSpacing  # set contour spacing
        else:
            resources.cnLevelSpacingF = cspace  # set contour spacing

    resources.lbOrientation = "Horizontal"  # Default is vertical.
    resources.lbBoxLinesOn = False
    resources.lbLabelFontHeightF = 0.01  # label font height
    resources.lbBoxMinorExtentF = 0.15

    #
    # The contour plot is not very interesting, so don't draw it.
    #
    resources.nglDraw = False
    resources.nglFrame = False

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

    #
    # Retrieve the actual lat/lon end points of the scalar array so
    # we know where to overlay on map.
    #
    xs = Ngl.get_float(contour.sffield, "sfXCActualStartF")
    xe = Ngl.get_float(contour.sffield, "sfXCActualEndF")
    ys = Ngl.get_float(contour.sffield, "sfYCActualStartF")
    ye = Ngl.get_float(contour.sffield, "sfYCActualEndF")

    resources.nglDraw = True  # Turn these resources back on.
    resources.nglFrame = True

    resources.mpProjection = "Robinson"
    resources.mpCenterLonF = 270
    resources.mpCenterLatF = 0

    resources.mpGeophysicalLineThicknessF = 2

    map = Ngl.contour_map(wks, var, resources)

    Ngl.end()
Esempio n. 33
0
def plot_Robinson_pyngl(var,lon,lat,wks_name='plot', clim=None, cspace=None, cmap=None):

    #
    #  Select a colormap and open a workstation.
    #
    rlist            = Ngl.Resources()

    wks_type = "png"
    wks = Ngl.open_wks(wks_type,wks_name,rlist)

    if cmap is None:
        mycmap = 'BlAqGrYeOrReVi200'
        Ngl.define_colormap(wks,mycmap)
    else:
        try:
            mycmap = '/Users/frederic/python/cmap/' + cmap    
            mycmap = np.loadtxt(mycmap)
        except:
            mycmap = cmap
        try:
            Ngl.define_colormap(wks,mycmap)
        except:
            raise Warning, 'Unknown colormap'

    #
    #  The next set of resources will apply to the contour plot and the labelbar.
    #
    resources = Ngl.Resources()

    resources.sfXArray            = lon
    resources.sfYArray            = lat

    resources.gsnMaximize         = True                # use full page


    resources.cnFillOn            = True
    resources.cnFillMode          = "RasterFill"
    resources.cnMaxLevelCount     = 255 
    resources.cnLinesOn           = False
    resources.cnLineLabelsOn      = False
    if clim is not None:
        resources.cnLevelSelectionMode = "ManualLevels"          # set manual contour levels
        resources.cnMinLevelValF       = clim[0]                 # set min contour level
        resources.cnMaxLevelValF       = clim[1]                 # set max contour level
        if cspace is None:
            LevelSpacing = (clim[1] - clim[0]) / 100.
            resources.cnLevelSpacingF      =  LevelSpacing       # set contour spacing
        else:
            resources.cnLevelSpacingF      =  cspace             # set contour spacing

    resources.lbOrientation      = "Horizontal"     # Default is vertical.
    resources.lbBoxLinesOn       = False
    resources.lbLabelFontHeightF = 0.01            # label font height
    resources.lbBoxMinorExtentF  = 0.15

    #
    # The contour plot is not very interesting, so don't draw it.
    # 
    resources.nglDraw  = False
    resources.nglFrame = False

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

    #
    # Retrieve the actual lat/lon end points of the scalar array so
    # we know where to overlay on map.
    #
    xs = Ngl.get_float(contour.sffield,"sfXCActualStartF")
    xe = Ngl.get_float(contour.sffield,"sfXCActualEndF")
    ys = Ngl.get_float(contour.sffield,"sfYCActualStartF")
    ye = Ngl.get_float(contour.sffield,"sfYCActualEndF")

    resources.nglDraw           = True        # Turn these resources back on.
    resources.nglFrame          = True

    resources.mpProjection      = "Robinson"
    resources.mpCenterLonF = 270
    resources.mpCenterLatF =   0

    resources.mpGeophysicalLineThicknessF = 2

    map = Ngl.contour_map(wks,var,resources)

    Ngl.end()
Esempio n. 34
0
resources.sfXArray = lon  # Portion of map on which to overlay
resources.sfYArray = lat  # contour plot.
resources.sfElementNodes = ele
resources.sfFirstNodeIndex = 1

resources.cnFillOn = True
resources.cnLinesOn = False
resources.cnLineLabelsOn = False

#
# This plot isn't very interesting because it isn't overlaid on a map.
# We are only creating it so we can retrieve information that we need
# to overlay it on a map plot later. You can turn off this plot
# by setting the nglDraw and nglFrame resources to False.
#
contour = Ngl.contour(wks, depth, resources)

#
#  The next set of resources will apply to the map plot.
#
resources.mpProjection = "CylindricalEquidistant"

#
# Once the high resolution coastline data files have been
# downloaded (see the Notes section above for details), to
# access them you need to change the following resource
# to "HighRes".
#
resources.mpDataBaseVersion = "MediumRes"

#
def plot_psirr_lines(vpx=0.2, vpy=0.8, hei=0.4, xlab=1,ylab=1):
   
   psi_levels = np.array([-500,-50])
   
   if(1):
      
      if(1):
         
         res = Ngl.Resources()
         
         res.nglMaximize                      =  False
         res.nglPaperOrientation              =  'Portrait'
         res.nglFrame                         =  False
         res.nglDraw                          =  False
         
         res.cnFillOn                         =  False
         res.cnLinesOn                        =  True
         res.cnLineLabelsOn                   =  True
         res.cnLineLabelDensityF              =  2
         res.cnLineLabelBackgroundColor       =  -1
         res.cnLevelSelectionMode             =  'ExplicitLevels'
         res.cnLevels                         =  psi_levels
         res.cnMonoLineColor                  =  True
         res.cnLineColor                      =  'blue'
         res.cnLineThicknessF                 =  2
         res.cnInfoLabelOn                    =  False
         
         res.sfXArray                         =  vx
         res.sfYArray                         =  vy
         
         res.trXMinF                          =  -3
         res.trXMaxF                          =  55
         res.trYMinF                          =  250
         res.trYMaxF                          =  360
         
         res.tiXAxisString                    =  'Latent heat [kJ/kg]'
         res.tiYAxisString                    =  'Dry static energy [kJ/kg]'
         res.tiMainString                     =  title
         
         if (xlab == 1):
            res.tiXAxisOn                     =  True
            res.tmXBLabelsOn                  =  True
            res.tiXAxisSide                   =  'Bottom'
         elif (xlab == -1):
            res.tiXAxisOn                      =  True
            res.tmXBLabelsOn                  =  False
            res.tmXTLabelsOn                  =  True
            res.tiXAxisSide                   =  'Top'
         elif (xlab == 0):
            res.tiXAxisOn                     =  False
            res.tmXBLabelsOn                  =  False
            res.tmXTLabelsOn                  =  False
            
         if (ylab == 1):
            res.tiYAxisOn                     =  True
            res.tmYLLabelsOn                  =  True
            res.tmYRLabelsOn                  =  False
            res.tiYAxisSide                   =  'Left'
         elif (ylab == -1):
            res.tiYAxisOn                     =  True
            res.tmYLLabelsOn                  =  False
            res.tmYRLabelsOn                  =  True
            res.tiYAxisSide                   =  'Right'
         elif (ylab == 0):
            res.tiYAxisOn                     =  False
            res.tmYLLabelsOn                  =  False
            res.tmYRLabelsOn                  =  False
            
         res.vpWidthF                         =  hei
         res.vpHeightF                        =  hei
         
         res.vpYF                             =  vpy
         res.vpXF                             =  vpx
         
         lsmooth = False
         if (lsmooth):
            sigma = 2
            order = 0
            for ji in range(0,2):
               ndimage.filters.gaussian_filter(zplot1[:,:],sigma,order=order,\
                                               output=zplot[:,:],\
                                               mode='reflect', cval=0.0)
         
         cont1 = Ngl.contour(wks,zplot1[:,:],res)
         
         ## Clausius-Clapeyron line
         vy_cc = np.linspace(240,360,101)
         press = 101300.
         vx_cc,es = cclap(vy_cc*1000/1004.,press)
         vx_cc = 2.5 * 10**3 * vx_cc
         #ccstring = 'C-C, RH=100%'
         lres = Ngl.Resources()
         lres.gsLineDashPattern         =  15  
         lres.gsLineLabelFontHeightF    =  0.009
         lres.gsLineThicknessF          =  3
         #lres.gsLineLabelString         =  ccstring
         line = Ngl.add_polyline(wks,cont1,vx_cc,vy_cc,lres)
         
         ## MSE profiles
         lres = Ngl.Resources()
         lres.gsLineDashPattern         =  1
         lres.gsLineThicknessF          =  7  
         lres.gsLineColor               =  'blue'
         line = Ngl.add_polyline(wks,cont1,vlh1,vdse1,lres)
         
         
         res.cnLineColor = 'red'
         
         cont2 = Ngl.contour(wks,zplot2[:,:],res)
         
         ## MSE profiles
         lres = Ngl.Resources()
         lres.gsLineDashPattern         =  1
         lres.gsLineThicknessF          =  7  
         lres.gsLineColor               =  'red'
         line = Ngl.add_polyline(wks,cont2,vlh2,vdse2,lres)
         
         Ngl.overlay(cont2,cont1)
         Ngl.draw(cont2)
Esempio n. 36
0
mpres.mpMaskAreaSpecifiers = mask_specs  # areas to mask (protect)

#
# This set of resources deals with a map labelbar.
#
# Note that this is different from a contour labelbar
# (which we will turn off below), and we have more
# control over it (i.e. we can set the number of boxes,
# the fill # colors, etc) than we do with a contour labelbar.
#
mpres.pmLabelBarDisplayMode = "Always"  # Turn on a map labelbar

# Labelbar resources.
mpres.lbLabelStrings        = ["Ocean","Land","< 0","0-10","10-20","20-30",\
                               "30-40","40-50","50-60","60-70","70-80",    \
                               "80-90","90-100","> 100"]
mpres.lbFillColors = mp_fill_colrs + cn_fill_clrs

# Fill resources
cnres.cnFillColors = cn_fill_clrs
cnres.pmLabelBarDisplayMode = "Never"  # turn off, b/c map has one turned on

contour = Ngl.contour(wks, z[:, :], cnres)
map = Ngl.map(wks, mpres)

Ngl.overlay(map, contour)
Ngl.draw(map)
Ngl.frame(wks)

Ngl.end()
Esempio n. 37
0
#
resources = Ngl.Resources()

resources.sfXArray        = lat_t
resources.sfYArray        = z_t

resources.cnFillOn        = True
resources.cnFillPalette   = "gui_default"
resources.cnLineLabelsOn  = False

resources.tiMainString    = "Default axes"        # main title

#
# Draw the plot as is, with no transformations in place.
#
plot = Ngl.contour(wks,T,resources)

#
# Linearize the Y axis.
#
resources.tiMainString = "Y axis linearized"
resources.nglYAxisType = "LinearAxis"
plot = Ngl.contour(wks,T,resources)

#
# Linearize the X axis.
#
resources.tiMainString = "X and Y axes linearized"
resources.nglXAxisType = "LinearAxis"
plot = Ngl.contour(wks,T,resources)
def plot_power(Pow, symmetry=("symm"), source="", var1="", plotpath="./", flim=0.5, nWavePlt=20, cmin=0.05, cmax=0.55,
               cspc=0.05, plotxy=[1, 1], N=[1, 2]):

    dims = Pow.shape
    nplot = dims[0]

    FillMode = "AreaFill"

    # text labels
    abc = list(string.ascii_lowercase)

    # plot resources
    wkstype = "png"
    wks = ngl.open_wks(wkstype, plotpath + "SpaceTimePower_" + source + var1)
    plots = []

    # coherence2 plot resources
    res = coh_resources(cmin, cmax, cspc, FillMode, flim, nWavePlt)
    # phase arrow resources
    resA = phase_resources(flim, nWavePlt)

    # dispersion curve resources
    dcres = ngl.Resources()
    dcres.gsLineThicknessF = 2.0
    dcres.gsLineDashPattern = 0

    # text box resources
    txres = ngl.Resources()
    txres.txPerimOn = True
    txres.txFontHeightF = 0.013
    txres.txBackgroundFillColor = "Background"

    # panel plot resources
    resP = panel_resources(nplot, abc)

    # plot contours and phase arrows
    pp = 0
    while pp < nplot:
        if nplot == 1:
            coh2 = Pow
        else:
            coh2 = Pow[pp, :, :]
        if len(symmetry) == nplot:
            Symmetry = symmetry[pp]
        else:
            Symmetry = symmetry

        res.tiMainString = source + "    log10( Power(" + var1 + "))           " + Symmetry
        plot = ngl.contour(wks, coh2, res)

        (matsuno_names, textlabels, textlocsX, textlocsY) = text_labels(Symmetry)
        nlabel = len(textlocsX)

        # generate matsuno mode dispersion curves
        if Symmetry == "midlat":
            He = [3000, 7000, 10000]
            matsuno_modes = mp.matsuno_modes_wk_bg(he=He, n=N, latitude=0., max_wn=nWavePlt, n_wn=500, u=25)
        else:
            He = [12, 25, 50]
            matsuno_modes = mp.matsuno_modes_wk(he=He, n=N, latitude=0., max_wn=nWavePlt, n_wn=500)

        # add polylines for dispersion curves
        for he in matsuno_modes:
            df = matsuno_modes[he]
            wn = df.index.values
            for wavename in df:
                for matsuno_name in matsuno_names:
                    if wavename == (matsuno_name + str(he) + "m)"):
                        wave = df[wavename].values
                        wnwave = wn[~np.isnan(wave)]
                        wave = wave[~np.isnan(wave)]
                        ngl.add_polyline(wks, plot, wnwave, wave, dcres)

        # add text boxes
        ll = 0
        while ll < nlabel:
            ngl.add_text(wks, plot, textlabels[ll], textlocsX[ll], textlocsY[ll], txres)
            ll += 1

        plots.append(plot)
        pp += 1

        # panel plots
    ngl.panel(wks, plots, plotxy, resP)
    ngl.delete_wks(wks)
    #ngl.end()

    return
Esempio n. 39
0
jspn = numpy.power(xrange(-M / 2 + 5, M / 2 + 5), 2)
ispn = numpy.power(xrange(-N / 2 - 3, N / 2 - 3), 2)
for i in xrange(len(ispn)):
    T[i, :] = ispn[i] + jspn
T = 100. - 8. * numpy.sqrt(T)

#
#  Open a workstation and draw a contour plot.
#
wks_type = "png"
wks = Ngl.open_wks(wks_type, "cns01p")

res = Ngl.Resources()
res.cnMonoLineDashPattern = False

plot1 = Ngl.contour(wks, T, res)

#
#  Retrieve the automatically set line labels.
#  These will be: ['-80', '-60', '-40', '-20', '0', '20', '40', '60', '80']
#
line_labels1 = Ngl.get_string_array(plot1, "cnLineLabelStrings")

#
#  Set explicit line labels.  Notice that the dash line
#  setting carries over from the first plot.
#
res.cnExplicitLineLabelsOn = True
res.cnLineLabelStrings = [
    "Lab1", "Lab2", "Lab3", "Lab4", "Lab5", "Lab6", "Lab7", "Lab8", "Lab9"
]
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)
Esempio n. 41
0
resources.cnLinesOn             = False
resources.cnLineLabelsOn        = False
resources.cnLevelSelectionMode  = "ExplicitLevels"
resources.cnLevels              = [ 1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,15.,20.,
                                   25.,30.,35.,40.,45.,50.,100.,200.,300.,400.,
                                   500.,600.,700.,800.,900.,1000.,1250.,1500.,
                                   1750.,2000.,2250.,2500.,2750.,3000.,3250.,
                                   3500.,3750.,4000.,4250.,4500.,4750.,5000.]

resources.tiMainString          = "North Carolina Coast (depth in meters)"
resources.tiMainFontHeightF     = 0.015

resources.nglDraw               = False
resources.nglFrame              = False

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

#
# Retrieve the actual lat/lon end points of the scalar array so
# we know where to overlay on map.
#
xs = Ngl.get_float(contour.sffield,"sfXCActualStartF")
xe = Ngl.get_float(contour.sffield,"sfXCActualEndF")
ys = Ngl.get_float(contour.sffield,"sfYCActualStartF")
ye = Ngl.get_float(contour.sffield,"sfYCActualEndF")

#
#  The next set of resources will apply to the map plot.
#
resources.mpProjection          = "CylindricalEquidistant"
Esempio n. 42
0
File: seam.py Progetto: akrherz/me
resources.cnFillOn            = True
resources.cnFillMode          = "AreaFill"
resources.cnLinesOn           = False
resources.cnLineLabelsOn      = False

resources.lbBoxLinesOn        = False
resources.lbLabelFontHeightF  = 0.015
resources.tiMainString        = "HOMME grid - surface pressure (mb)"

#
# The contour plot is not very interesting, so don't draw it.
# 
resources.nglDraw  = False
resources.nglFrame = False

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

#
# Retrieve the actual lat/lon end points of the scalar array so
# we know where to overlay on map.
#
xs = Ngl.get_float(contour.sffield,"sfXCActualStartF")
xe = Ngl.get_float(contour.sffield,"sfXCActualEndF")
ys = Ngl.get_float(contour.sffield,"sfYCActualStartF")
ye = Ngl.get_float(contour.sffield,"sfYCActualEndF")

resources.nglDraw           = True        # Turn these resources back on.
resources.nglFrame          = True

resources.mpProjection      = "Orthographic"
resources.mpDataBaseVersion = "MediumRes"
Esempio n. 43
0
#
N=25
 
T = numpy.zeros((N,N),'f')
 
jspn = numpy.power(numpy.arange(-12,13),2)
ispn = numpy.power(numpy.arange(-12,13),2)

for i in range(0,len(ispn)):
  T[i,:] = (jspn + ispn[i]).astype('f')

T = 100.0 - numpy.sqrt(64 * T)

wks_type = "png"
wks = Ngl.open_wks(wks_type,"contour1")

cnres = Ngl.Resources()
cnres.sfYCStartV    = 10         # Define limits for Y axis.
cnres.sfYCEndV      = 1000
cnres.tiXAxisString = "linear"   # Label for X axis.
cnres.tiYAxisString = "linear"   # Label for Y axis.

contour = Ngl.contour(wks,T,cnres)  # Create and draw contour plot.

cnres.tiYAxisString = "log"    # Label for Y axis.
cnres.trYLog        = True     # Log scaling for Y axis

contour = Ngl.contour(wks,T,cnres)  # Create and draw contour plot.

Ngl.end()
res.cnFillOn = True  #-- turn on contour fill.
res.cnLineLabelsOn = False  #-- turn off line labels.
res.cnInfoLabelOn = False  #-- turn off info label.
res.cnFillPalette = "BlueWhiteOrangeRed"  #-- set color map.
res.pmLabelBarOrthogonalPosF = -0.03  #-- move labelbar close to plot

res.sfXArray = lon  #-- scalar field x
res.sfYArray = lev  #-- scalar field y

res.trYReverse = True  #-- reverse the Y axis
res.nglYAxisType = "LogAxis"  #-- y axis log

res.tiYAxisString = "%s (hPa)" % f.variables["lev"].long_name

res.nglPointTickmarksOutward = True  #-- point tickmarks out

res.tmYLMode = "Explicit"  #-- set y axis tickmark labels
res.tmXBMode = "Explicit"  #-- set x axis tickmark labels
res.tmYLValues = levs
res.tmXBValues = lons
res.tmYLLabels = map(str, levs)
res.tmXBLabels = nice_lon_labels(lons)

res.tmXBLabelFontHeightF = 0.015  # - make font smaller
res.tmYLLabelFontHeightF = 0.015

map = Ngl.contour(wks, t26, res)  #-- draw contours

#-- end
Ngl.end()
Esempio n. 45
0
File: cns01p.py Progetto: akrherz/me
#            to their defaults.
#
import Ngl
import Numeric

M=29
N=25
T = Numeric.zeros([N,M])
 
#
# create a mound as a test data set
#
jspn = Numeric.power(xrange(-M/2+5,M/2+5),2)
ispn = Numeric.power(xrange(-N/2-3,N/2-3),2)
for i in xrange(len(ispn)):
  T[i,:] = ispn[i] + jspn
T = 100. - 8.*Numeric.sqrt(T)

#
#  Open a workstation and draw the contour plot.
#
wks_type = "ps"
wks = Ngl.open_wks(wks_type,"cns01p")

res = Ngl.Resources()
res.cnMonoLineDashPattern = False

Ngl.contour(wks,T,res)

Ngl.end()
Esempio n. 46
0
res.cnLineLabelsOn             = True
res.cnLinesOn                  = True
res.cnMonoLineLabelFontColor   = True
res.lbLabelFontHeightF         = 0.0075
res.cnLineThicknessF           = 2.5
res.cnInfoLabelOn              = True
res.cnInfoLabelString          = "CIN Contours at -50, -100 and -250 J/Kg"
res.cnInfoLabelOrthogonalPosF  = -0.06
res.cnInfoLabelParallelPosF    = 0.505
 
res.cnLevelSelectionMode = "ExplicitLevels"
res.cnLevels = [-250.0, -100.0, -50.0]

# plot CIN and overlay on colour contours

CIN_plot = ngl.contour(wks,CIN,res)

ngl.overlay(CAPE_plot,CIN_plot)

ngl.maximize_plot(wks, CAPE_plot)
ngl.draw(CAPE_plot)
ngl.frame(wks)

ngl.destroy(wks)
del res
del CAPE
del CIN

###################################################################################################

# open forecast file
Esempio n. 47
0
File: cns01p.py Progetto: yyr/pyngl
jspn = numpy.power(xrange(-M/2+5,M/2+5),2)
ispn = numpy.power(xrange(-N/2-3,N/2-3),2)
for i in xrange(len(ispn)):
  T[i,:] = ispn[i] + jspn
T = 100. - 8.*numpy.sqrt(T)

#
#  Open a workstation and draw a contour plot.
#
wks_type = "ps"
wks = Ngl.open_wks(wks_type,"cns01p")

res = Ngl.Resources()
res.cnMonoLineDashPattern = False

plot1 = Ngl.contour(wks,T,res)

# 
#  Retrieve the automatically set line labels.  
#  These will be: ['-80', '-60', '-40', '-20', '0', '20', '40', '60', '80']
#
line_labels1 = Ngl.get_string_array(plot1,"cnLineLabelStrings")

#
#  Set explicit line labels.  Notice that the dash line
#  setting carries over from the first plot.
#
res.cnExplicitLineLabelsOn = True
res.cnLineLabelStrings = ["Lab1",  "Lab2", "Lab3", "Lab4", "Lab5",
                          "Lab6",  "Lab7", "Lab8", "Lab9"]
plot2 = Ngl.contour(wks,T,res)
Esempio n. 48
0
resources.cnFillOn              = True     # Turn on contour fill.
resources.cnInfoLabelOn         = False    # Turn off info label.
resources.cnLineLabelsOn        = False    # Turn off line labels.

resources.lbOrientation         = "Horizontal"   # Draw labelbar horizontally.

resources.nglSpreadColors = False         # Do not interpolate color space.
resources.vpYF            = 0.9           # Change Y location of plot.

#
#  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.
Esempio n. 49
0
cnres.nglMaximize = True  # Maximize plot in frame
cnres.nglDraw = False  # Don't draw plot
cnres.nglFrame = False  # Don't advance the frame

cnres.cnFillOn = True  # Turn on contour fill
cnres.cnFillPalette = cmap[:-3, :]

cnres.cnLevelSelectionMode = "ManualLevels"
cnres.cnLevelSpacingF = nice_spc
cnres.cnMinLevelValF = nice_min
cnres.cnMaxLevelValF = nice_max

cnres.lbOrientation = "Vertical"  # Default is horizontal

cnres.tiMainString = "This is a title"
cnres.tiXAxisString = "X axis"
cnres.tiYAxisString = "Y axis"

contourplot = Ngl.contour(wks, data, cnres)

# Draw plot with viewport and bounding boxes.
Ngl.draw(contourplot)
draw_bb_box(wks, contourplot)
draw_vp_box(wks, contourplot)

# Advance frame.
Ngl.frame(wks)

Ngl.end()
Esempio n. 50
0
resources.cnLineLabelsOn = False  # Turn off contour labels

#
# Set some font heights to make them slightly bigger than the default.
# Turn off nglScale, because this resource wants to set the axes font
# heights for you.
#
resources.nglScale = False
resources.tiMainFontHeightF = 0.037
resources.lbLabelFontHeightF = 0.032
resources.tmXBLabelFontHeightF = 0.030
resources.tmYLLabelFontHeightF = 0.030

for i in range(0, nplots):
    resources.tiMainString = "Temperature at time = {}".format(i)
    plot.append(Ngl.contour(wks, temp[i, :, :], resources))

Ngl.panel(wks, plot[0:4], [2, 2])  # Draw 2 rows/2 columns of plots.

#
# Now add some extra white space around each plot.
#

panelres = Ngl.Resources()
panelres.nglPanelYWhiteSpacePercent = 5.
panelres.nglPanelXWhiteSpacePercent = 5.
Ngl.panel(wks, plot[0:4], [2, 2], panelres)  # Draw 2 rows/2 columns of plots.

#
# This section will set resources for drawing contour plots over a map.
#
Esempio n. 51
0
res.sfXArray = FEDU_Alpha 
res.sfYArray = energy_lev 
res.cnExplicitLabelBarLabelsOn = True
res.lbLabelStrings = ("1","10","100","1e3","1e4","1e5")
res.cnLevelSelectionMode = 'ExplicitLevels'
#res.cnMinLevelValF = 0. 
#res.cnMaxLevelValF = 1.e8
res.cnLevels = (1., 10., 100., 1000., 10000., 100000.)
#res.cnLevels = ( 1, 1e2, 1e3, 1e4, 1e5, 1e6)
#res.cnLevels = np.logspace(1, 6, num=12)
res.cnFillMode = 'CellFill'
res.tmXBMode = 'Explicit'
res.tmXBValues = (8, 25, 41, 57, 74, 90, 106, 123, 139, 155, 172)
res.tmXBLabels = ("8", "25", "41", "57", "74", "90", "106", "123", "139", "155", "172")

Ngl.contour(wks,FEDU_plot[0:20,:],res)


# ------------------------------------------
# Plot RBSP for 8 degree pitch 
# ------------------------------------------ 

wks_type = "ps"
wks2 = Ngl.open_wks(wks_type,"RBSP_8degree")

res2 = Ngl.Resources()
res2.cnFillOn           = True    # turn on color fill
res2.cnLineLabelsOn     = False   # turn off contour line labels
res2.lbLabelFontHeightF = 0.018   # make labelbar labels smaller
#res2.sfXArray = Epoch 
res2.sfYArray = energy_lev 
def grid_order_contourplot(model, grid, first_varying_var, cut_domain):

    # define paths #

    path = dict(base='/', plots='data/plots/experimental/gridpoint_order/')
    print('plotting model: {}'.format(model))

    # load icosahedral grid information #

    if grid == 'icosahedral':
        clat, clon, vlat, vlon = read_grid_coordinates(model, grid)
        data_array1 = np.arange(clat.shape[0], dtype='float32')
    else:
        clat, clon = read_grid_coordinates(model, grid)
        clon = clon - 180
        if first_varying_var == 'lon':
            data_array1 = np.arange(clat.shape[0] * clon.shape[0],
                                    dtype='float32').reshape(
                                        (clat.shape[0], clon.shape[0]))
        elif first_varying_var == 'lat':
            data_array1 = np.arange(clat.shape[0] * clon.shape[0],
                                    dtype='float32').reshape(
                                        (clon.shape[0], clat.shape[0])).T

    print('data_array1:', data_array1.shape, 'clat:', clat.shape, 'clon:',
          clon.shape)
    if grid == 'icosahedral':
        print('vlat:', vlat.shape, 'vlon:', vlon.shape)
    print('data_array1 min,max:', data_array1.min(), data_array1.max())
    print('clat min,max:', clat.min(), clat.max())
    print('clon min,max:', clon.min(), clon.max())
    if grid == 'icosahedral':
        print('vlat min,max:', vlat.min(), vlat.max())
        print('vlon min,max:', vlon.min(), vlon.max())
    print('------------------------------------------')

    if cut_domain['name'] == 'uncut':
        data_array1_cut = data_array1
    else:
        margin_deg = 0
        if grid == 'icosahedral':
            data_array1_cut, clat, clon, vlat, vlon \
              = cut_by_domain(cut_domain, grid, data_array1, clat, clon, vlat, vlon, margin_deg)
        else:
            data_array1_cut, clat, clon \
              = cut_by_domain(cut_domain, grid, data_array1, clat, clon, None, None, margin_deg)

    print('data_array1:', data_array1_cut.shape, 'clat:', clat.shape, 'clon:',
          clon.shape)
    if grid == 'icosahedral':
        print('vlat:', vlat.shape, 'vlon:', vlon.shape)
    print('data_array1_cut min,max:', data_array1_cut.min(),
          data_array1_cut.max())
    print('clat min,max:', clat.min(), clat.max())
    print('clon min,max:', clon.min(), clon.max())
    if grid == 'icosahedral':
        print('vlat min,max:', vlat.min(), vlat.max())
        print('vlon min,max:', vlon.min(), vlon.max())

    if grid == 'icosahedral':
        plot_name = 'gridpoint_order_{}_{}_global_{}'.format(
            model, grid, cut_domain['name'])
    else:
        plot_name = 'gridpoint_order_{}_{}_{}-varying-first_global_{}'.format(
            model, grid, first_varying_var, cut_domain['name'])

    # plot basic map with borders #

    wks_res = Ngl.Resources()
    x_resolution = 800
    y_resolution = 800
    wks_res.wkWidth = x_resolution
    wks_res.wkHeight = y_resolution

    wks_res.wkColorMap = 'BkBlAqGrYeOrReViWh200'
    levels1 = np.linspace(data_array1.min(), data_array1.max(), 200)

    wks_type = 'png'
    wks = Ngl.open_wks(wks_type, path['base'] + path['plots'] + plot_name,
                       wks_res)

    mpres = Ngl.Resources()
    mpres.mpProjection = 'CylindricalEquidistant'
    mpres.mpLimitMode = 'LatLon'
    mpres.mpCenterLonF = 0.0
    mpres.mpCenterLatF = 0.0
    mpres.mpMinLonF = -180.
    mpres.mpMaxLonF = 180.
    mpres.mpMinLatF = -90.
    mpres.mpMaxLatF = 90.

    mpres.nglMaximize = False
    mpres.vpXF = 0.003
    mpres.vpYF = 1.00
    mpres.vpWidthF = 0.86
    mpres.vpHeightF = 1.00
    mpres.mpMonoFillColor = 'True'
    mpres.mpFillColor = -1

    #Ngl.set_values(wks,mpres)
    mpres.mpFillOn = True
    #resources.cnFillDrawOrder   = 'Predraw'     # draw contours first
    mpres.mpGridAndLimbOn = False
    mpres.mpGreatCircleLinesOn = False

    #mpres.mpOutlineDrawOrder       = 'PreDraw'
    mpres.mpDataBaseVersion = 'LowRes'
    mpres.mpDataSetName = 'Earth..4'
    mpres.mpOutlineBoundarySets = 'national'
    mpres.mpGeophysicalLineColor = 'black'
    mpres.mpNationalLineColor = 'black'
    mpres.mpGeophysicalLineThicknessF = 2. * x_resolution / 1000
    mpres.mpNationalLineThicknessF = 2. * x_resolution / 1000

    mpres.mpPerimOn = True
    mpres.mpPerimLineColor = 'black'
    mpres.mpPerimLineThicknessF = 8.0 * x_resolution / 1000
    mpres.tmXBOn = False
    mpres.tmXTOn = False
    mpres.tmYLOn = False
    mpres.tmYROn = False

    mpres.nglDraw = False  #-- don't draw plot
    mpres.nglFrame = False  #-- don't advance frame

    basic_map = Ngl.map(wks, mpres)

    # plot variable1 in shading/contours #

    v1res = Ngl.Resources()
    v1res.sfDataArray = data_array1_cut
    v1res.sfXArray = clon
    v1res.sfYArray = clat
    if grid == 'icosahedral':
        v1res.cnFillMode = 'CellFill'
        v1res.sfXCellBounds = vlon
        v1res.sfYCellBounds = vlat
    else:
        v1res.cnFillMode = 'RasterFill'
    v1res.sfMissingValueV = 9999

    v1res.cnLinesOn = False  # Turn off contour lines.
    v1res.cnFillOn = True
    #v1res.cnFillOpacityF        = 0.5
    #v1res.cnFillDrawOrder       = 'Predraw'
    v1res.cnLineLabelsOn = False
    v1res.cnLevelSelectionMode = 'ExplicitLevels'
    v1res.cnLevels = levels1

    # set resources for a nice label bar #

    v1res.lbLabelBarOn = True
    v1res.lbAutoManage = False
    v1res.lbOrientation = 'vertical'
    v1res.lbLabelOffsetF = 0.04  # minor axis fraction: the distance between colorbar and numbers
    v1res.lbBoxMinorExtentF = 0.20  # minor axis fraction: width of the color boxes when labelbar down
    v1res.lbTopMarginF = 0.05  # make a little more space at top for the unit label
    v1res.lbRightMarginF = 0.0
    v1res.lbBottomMarginF = 0.0
    v1res.lbLeftMarginF = -0.35

    v1res.cnLabelBarEndStyle = 'ExcludeOuterBoxes'
    #v1res.cnLabelBarEndStyle    = 'IncludeOuterBoxes'
    #v1res.cnExplicitLabelBarLabelsOn = True
    #v1res.pmLabelBarDisplayMode =  'Always'
    v1res.pmLabelBarWidthF = 0.10
    #v1res.lbLabelStrings        = label_str_list
    v1res.lbLabelFontHeightF = 0.010
    #v1res.lbBoxCount            = 40
    v1res.lbBoxSeparatorLinesOn = False
    v1res.lbBoxLineThicknessF = 4
    #v1res.lbBoxEndCapStyle     = 'TriangleBothEnds'
    v1res.lbLabelAlignment = 'InteriorEdges'
    v1res.lbLabelStride = 1

    v1res.nglFrame = False
    v1res.nglDraw = False

    v1plot = Ngl.contour(wks, data_array1_cut, v1res)

    # plot label bar unit #

    text_str = 'Index'
    text_res_1 = Ngl.Resources()
    text_res_1.txFontColor = 'black'
    text_x = 0.975
    text_y = 0.72
    text_res_1.txFontHeightF = 0.012

    Ngl.overlay(basic_map, v1plot)

    Ngl.draw(basic_map)
    Ngl.text_ndc(wks, text_str, text_x, text_y, text_res_1)
    Ngl.frame(wks)
    Ngl.destroy(wks)
    #Ngl.end()

    # cut top and bottom whitespace of plot #

    im = Image.open(path['base'] + path['plots'] + plot_name + '.png')
    image_array = np.asarray(im.convert('L'))
    image_array = np.where(image_array < 255, 1, 0)
    image_filter = np.amax(image_array, axis=1)
    vmargins = [
        np.nonzero(image_filter)[0][0],
        np.nonzero(image_filter[::-1])[0][0]
    ]
    #print(vmargins)
    #print(im.size)

    im_cropped = Image.new(
        'RGB', (im.size[0], im.size[1] - vmargins[0] - vmargins[1]),
        (255, 255, 255))
    im_cropped.paste(
        im.crop((0, vmargins[0], im.size[0], im.size[1] - vmargins[1])),
        (0, 0))
    #print(im_cropped.size)
    im.close()
    im_cropped.save(path['base'] + path['plots'] + plot_name + '.png', 'png')
    im_cropped.close()

    del data_array1, data_array1_cut, clat, clon
    if grid == 'icosahedral':
        del vlat, vlon

    return
Esempio n. 53
0
cfres.lbOrientation             = "Horizontal"  # horizontal labelbar
cfres.lbLabelFontHeightF        = 0.012         # Decrease font size.
cfres.pmLabelBarOrthogonalPosF  = -0.05         # Move labelbar up.

clres.cnLineLabelsOn            = False         # Turn off contour line labels.
clres.cnLineDashPatterns        = 3             # dashed contour lines
clres.cnLineThicknessF          = 3.            # triple thick contour lines
clres.cnInfoLabelOrthogonalPosF = -0.15         # Move info label up.

#
# Create the various plots. They will not get drawn because
# nglDraw is set to False for all of them.
#
map_plot          = Ngl.map(wks,mpres)
vector_plot       = Ngl.vector(wks,ua,va,vcres)
line_contour_plot = Ngl.contour(wks,pa,clres)
fill_contour_plot = Ngl.contour(wks,ta,cfres)

#
# Overlay everything on the map plot.
#
Ngl.overlay(map_plot,fill_contour_plot)
Ngl.overlay(map_plot,line_contour_plot)
Ngl.overlay(map_plot,vector_plot)

#
# Change the title.
#
srlist = Ngl.Resources()
srlist.tiMainString = "vectors, line, and filled contours"
Ngl.set_values(map_plot,srlist)
Esempio n. 54
0
resources.cnFillMode = "AreaFill"
resources.cnFillPalette = "BlAqGrYeOrReVi200"
resources.cnLinesOn = False
resources.cnLineLabelsOn = False

resources.lbBoxLinesOn = False
resources.lbLabelFontHeightF = 0.015
resources.tiMainString = "HOMME grid - surface pressure (mb)"

#
# The contour plot is not very interesting, so don't draw it.
#
resources.nglDraw = False
resources.nglFrame = False

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

#
# Retrieve the actual lat/lon end points of the scalar array so
# we know where to overlay on map.
#
xs = Ngl.get_float(contour.sffield, "sfXCActualStartF")
xe = Ngl.get_float(contour.sffield, "sfXCActualEndF")
ys = Ngl.get_float(contour.sffield, "sfYCActualStartF")
ye = Ngl.get_float(contour.sffield, "sfYCActualEndF")

resources.nglDraw = True  # Turn these resources back on.
resources.nglFrame = True

resources.mpProjection = "Orthographic"
resources.mpDataBaseVersion = "MediumRes"
Esempio n. 55
0
rres = Ngl.Resources()
rres.nglDraw = False  #-- don't draw plot
rres.nglFrame = False  #-- don't advance frame

rres.cnInfoLabelOrthogonalPosF = 0.13  #-- move info label upward

rres.sfXArray = lon
rres.sfYArray = lat

#-- generate tplot, but don't draw it yet
print("-- map --")
map = Ngl.map(wks, mpres)

#-- generate tplot, but don't draw it yet
print("-- tplot --")
tplot = Ngl.contour(wks, t, tres)

#-- generate plot2, but don't draw it yet
print("-- rplot --")
rplot = Ngl.contour(wks, rhum, rres)

#-- overlay rplot on tplot
print("-- overlay tplot --")
Ngl.overlay(map, tplot)
print("-- overlay rplot --")
Ngl.overlay(map, rplot)

#-- draw the plot
Ngl.draw(map)

#-- write variable long_name and units to the plot
Esempio n. 56
0
File: cn01p.py Progetto: yyr/pyngl
#     Drawing a contour visualization using all defaults.
# 
#  Output:
#     A single visualization is produced.
#
#
import Ngl
import numpy

M=29
N=25
T = numpy.zeros([N,M])
 
#
# create a mound as a test data set
#
jspn = numpy.power(xrange(-M/2+5,M/2+5),2)
ispn = numpy.power(xrange(-N/2-3,N/2-3),2)
for i in xrange(len(ispn)):
  T[i,:] = ispn[i] + jspn
T = 100. - 8.*numpy.sqrt(T)

#
#  Open a workstation and draw the contour plot.
#
wks_type = "ps"
wks = Ngl.open_wks(wks_type,"cn01p")
Ngl.contour(wks,T)

Ngl.end()