Example #1
0
def tricolour(wks, xll, yll, height):
    #
    #  Colors
    #
    blue_index = Ngl.new_color(wks, 0.00, 0.15, 0.50)
    white_index = Ngl.new_color(wks, 1.00, 1.00, 1.00)
    red_index = Ngl.new_color(wks, 1.00, 0.10, 0.14)
    width = 1.5 * height
    xx = numpy.zeros(5, 'f')
    yy = numpy.zeros(5, 'f')
    #
    #  Draw blue bar.
    #
    xx = [xll, xll + width / 3., xll + width / 3., xll, xll]
    yy = [yll, yll, yll + height, yll + height, yll]
    pres = Ngl.Resources()
    pres.gsFillColor = blue_index
    Ngl.polygon_ndc(wks, xx, yy, pres)
    #
    #  Draw white bar.
    #
    xx = [xll+width/3., xll + 2.*width/3., xll + 2.*width/3., \
             xll+width/3., xll+width/3.]
    pres.gsFillColor = white_index
    Ngl.polygon_ndc(wks, xx, yy, pres)
    #
    #  Draw red bar.
    #
    xx = [xll+2.*width/3., xll + width, xll + width,  \
             xll+2.*width/3., xll+2.*width/3.]
    pres.gsFillColor = red_index
    Ngl.polygon_ndc(wks, xx, yy, pres)
    xx = [xll, xll + width, xll + width, xll, xll]
    #
    #  Perimeter.
    #
    pres.gsLineColor = 1
    Ngl.polyline_ndc(wks, xx, yy, pres)
Example #2
0
wks = Ngl.open_wks(wks_type,"ngl05p")

#----------- Begin first plot -----------------------------------------
 
resources = Ngl.Resources()

resources.sfXCStartV = float(min(psl_lon))
resources.sfXCEndV   = float(max(psl_lon))
resources.sfYCStartV = float(min(psl_lat))
resources.sfYCEndV   = float(max(psl_lat))

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

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

ic = Ngl.new_color(wks,0.75,0.75,0.75)   # Add gray to the color map

resources.mpProjection = "Orthographic" # Change the map projection.
resources.mpCenterLonF = 180.           # Rotate the projection.
resources.mpFillOn     = True           # Turn on map fill.
resources.mpFillColors = [0,-1,ic,-1]   # Fill land and leave oceans
                                        # and inland water transparent.

resources.vpXF      = 0.1    # Change the size and location of the
resources.vpYF      = 0.9    # plot on the viewport.
resources.vpWidthF  = 0.7
resources.vpHeightF = 0.7

mnlvl = 0                        # Minimum contour level.
mxlvl = 28                       # Maximum contour level.
spcng = 2                        # Contour level spacing.
Example #3
0
#
#  Draw an orthographic map centered at lat/lon = (70.,-10.).
#  Don't advance the frame, since we want to add wind barbs.
#
mpres = Ngl.Resources()
#
# Define size of map in frame.
#
mpres.mpShapeMode = "FreeAspect"
mpres.vpXF = 0.06
mpres.vpYF = 0.94
mpres.vpWidthF = 0.42
mpres.vpHeightF = 0.42

mpres.nglFrame = False
gray_index = Ngl.new_color(wks, 0.7, 0.7, 0.7)
cyan_index = Ngl.new_color(wks, 0.5, 0.9, 0.9)
mpres.mpFillAreaSpecifiers = ["Water", "Land"]
mpres.mpSpecifiedFillColors = [cyan_index, gray_index]

mpres.mpLimitMode = "LatLon"
mpres.mpMinLonF = -40.
mpres.mpMaxLonF = 20.
mpres.mpMinLatF = 55.
mpres.mpMaxLatF = 85.
mpres.mpCenterLatF = 70.
mpres.mpCenterLonF = -10.
mpres.mpPerimOn = True
mpres.mpProjection = "Orthographic"
mpres.tiMainString = "Winds from the south"
mpres.tiMainFont = "Helvetica-Bold"
Example #4
0
mpres.cnFillColors         = [8,17,30,50,65,95,120,134,152,161]

mpres.pmTickMarkDisplayMode    = "Never"     # Don't draw tickmark border.

mpres.lbOrientation            = "Horizontal"    # put labelbar at bottom
mpres.pmLabelBarSide           = "Bottom"        # and horizontal
mpres.lbTitleString            = "Sea Surface Temperature Change (~S~o~N~C)"
mpres.lbTitlePosition          = "Bottom"
mpres.lbTitleFontHeightF       = 0.015
mpres.lbLabelFontHeightF       = 0.015
mpres.pmLabelBarOrthogonalPosF = 0.025  
        
map = Ngl.contour_map(wks,sst,mpres)      # Draw the first contours/map.

Ngl.define_colormap(wks,"WhViBlGrYeOrRe")   # set colormap for 2nd contours
igray = Ngl.new_color(wks,0.8,0.8,0.8)      # add gray

# Set up new contour resources

mpres.sfXArray          = Lon
mpres.sfYArray          = Lat

mpres.cnMinLevelValF    =  500.           # min contour level
mpres.cnMaxLevelValF    = 3500.           # max contour level
mpres.cnLevelSpacingF   =  500.           # contour spacing
mpres.cnFillColors      = [20,17,14,12,10,8,6,4]

mpres.lbOrientation      = "Vertical"      # vertical labelbar on 
mpres.pmLabelBarSide     = "Left"          # left side
mpres.lbTitleString      = "Ice Sheet Elevation (m)"
mpres.lbTitlePosition    = "Left"
Example #5
0
  delx_0, delx_1, dely_0, dely_1 = 0.245, 0.235, 0.22, 0.15

  x[0], y[0] = 0.015 + delx_0*(i%4), 0.90 - (i/4)*dely_0 
  x[1], y[1] = x[0] + delx_1       , y[0]
  x[2], y[2] = x[1]                , y[1] - dely_1
  x[3], y[3] = x[0]                , y[2]
  x[4], y[4] = x[0]                , y[0]

#
#  Convert the integer color values obtained from the
#  named color chart (as entered above) to floating 
#  point numbers in the range 0. to 1. (as required 
#  by "Ngl.new_color").
#
  r, g, b = colors[i][0]/255., colors[i][1]/255., colors[i][2]/255.
  poly_res.gsFillColor = Ngl.new_color(wks, r, g, b)
#
#  Draw a white outline if the color is black, otherwise draw a colored box.
#
  if (labels[i] == "Black"):
    Ngl.polyline_ndc(wks, x, y, poly_res)
  else:
    Ngl.polygon_ndc(wks, x, y, poly_res)
#
#  Label the boxes.
#
  text_res.txFontHeightF = 0.017
  Ngl.text_ndc(wks, labels[i], 0.5*(x[0]+x[1]), y[0] + 0.0125, text_res)
  rgb_label = "R=%4.2f G=%4.2f B=%4.2f" % (r, g, b)
  text_res.txFontHeightF = 0.015
  Ngl.text_ndc(wks, rgb_label, 0.5*(x[0]+x[1]), y[3] - 0.0125, text_res)
Example #6
0
def plot_oope_map(data, figname, size_class=None, percentage=1):

    ''' Draws 2D OOPE maps.

    :param xarray.Dataset data: 2D OOPE array. Dims must be (y, x, comm, size)
    :param str figname: Name of the figure file (must end by .png or .pdf)
    :param list size_class: Size classes to output (in m)
    :param float percentage: percentage used to saturate colorbar from percentile.
     Colorbar is saturated from values of the (X) and (100 - X) percentile.

    :return: None
    
    '''

    if size_class is None:
        size_class = [1e-3, 1e-2, 1e-1, 1]

    # sort size class in ascending order, and add 0 and infinity as size bounds
    size_class = np.sort(size_class)

    if size_class[0] != 0:
        size_class = np.concatenate(([0], size_class), axis=0)
    if size_class[-1] != np.Inf:
        size_class = np.concatenate((size_class, [np.Inf]), axis=0)

    # Check that the OOPE dataset has 4 dimensions (i.e. no time dimension)
    ndims = len(data['OOPE'].dims)

    if ndims != 4:
        message = 'Data must have dimensions of size (lat, lon, comm, wei)'
        print(message)
        sys.exit(0)

    # Recover data variables
    length = data['length'].values
    oope = data['OOPE'].values
    lon = data['longitude'][:].values
    lat = data['latitude'][:].values
    comm = data['community'][:].values.astype(np.int)

    # mask oope where land
    oope = np.ma.masked_where(np.isnan(oope), oope)

    comm_string = misc.extract_community_names(data)

    if figname.endswith('png'):
        form = 'png'
    elif figname.endswith('pdf'):
        form = 'pdf'
    else:
        message = 'Figure name should end with png or pdf'
        print(message)
        sys.exit(0)

    # opens the document
    wks = Ngl.open_wks(form, figname)

    # set the document colormap
    # resngl = Ngl.Resources()
    # resngl.wkColorMap = 'precip2_15lev'
    # Ngl.set_values(wks, resngl)

    # Add gray to the workspace
    Ngl.new_color(wks, 0.7, 0.7, 0.7)

    # init the plot resources
    # For a detailed description, see https://www.ncl.ucar.edu/Document/Graphics/Resources/
    res = Ngl.Resources()

    # not necessary, just a good habit
    res.nglDraw = False
    res.nglFrame = False

    # Set map resources.
    res.mpLimitMode = "LatLon"     # limit map via lat/lon
    res.mpMinLatF = lat.min()         # map area
    res.mpMaxLatF = lat.max()         # latitudes
    res.mpMinLonF = lon.min()         # and
    res.mpMaxLonF = lon.max()         # longitudes
    res.mpFillOn = True
    res.mpLandFillColor = "LightGray"
    res.mpOceanFillColor = -1
    res.mpInlandWaterFillColor = "LightBlue"
    res.mpGeophysicalLineThicknessF = 1  # thickness of coastlines

    # coordinates for contour plots
    res.sfXArray = lon
    res.sfYArray = lat

    res.cnFillOn = True  # filled contour
    res.cnLinesOn = False  # no lines
    res.cnLineLabelsOn = False  # no labels
    res.cnInfoLabelOn = False  # no info about contours

    res.cnFillMode = 'CellFill'  # contourf=AreaFill, pcolor="CellFill" or "RasterFill"
    res.lbOrientation = "Horizontal"  # colorbar orientation
    res.lbLabelFontHeightF = 0.012  # colorbar label fontsize
    res.lbTitlePosition = "Bottom"  # position of colorbar title
    res.lbTitleFontHeightF = 0.012  # title font height

    # res.cnFillPalette = "wgne15"
    res.cnFillPalette = "WhiteBlueGreenYellowRed"

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

    res.cnLevelSelectionMode = 'ExplicitLevels'
    res.cnMaxLevelCount = 41
    res.mpGridAndLimbOn = True

    # Equations are complicated with NCARG
    # see https://www.ncl.ucar.edu/Applications/fcodes.shtml
    res.lbTitleString = "OOPE (J.kg~S~-1~N~.m~S~-2~N~)"  # title of colorbar

    # Loop over communities
    for icom in comm:
        # Loop over size classes
        for isize in xrange(0, len(size_class) - 1):

            # Extract sizes comprised between the size class bound
            iw = np.nonzero((length >= size_class[isize]) & (length < size_class[isize+1]))[0]
            if iw.size == 0:
                continue

            # Integrate OOPE for the given community and given size class
            temp = oope[:, :, icom, iw]
            temp = np.sum(temp, axis=-1)

            # Finds the colorbar limits
            cmin, cmax = misc.find_percentile(temp, percentage=1)

            # draw the contour maps
            # defines the contour
            res.cnLevels = np.linspace(cmin, cmax, res.cnMaxLevelCount)
            mapplot = Ngl.contour_map(wks, temp, res)

            # add title
            title = 'Community=%s, %.2E m <= L < %.2E m' % (comm_string[icom], size_class[isize], size_class[isize + 1])
            Ngl.text_ndc(wks, title, 0.5, 0.85, txres)

            # draws the map
            Ngl.draw(mapplot)

            # add a page to the pdf output
            Ngl.frame(wks)