Exemple #1
0
def timeseries_analysis_plot(config,
                             dsvalues,
                             calendar,
                             title,
                             xlabel,
                             ylabel,
                             movingAveragePoints=None,
                             lineColors=None,
                             lineStyles=None,
                             markers=None,
                             lineWidths=None,
                             legendText=None,
                             maxPoints=None,
                             titleFontSize=None,
                             figsize=(15, 6),
                             dpi=None,
                             firstYearXTicks=None,
                             yearStrideXTicks=None,
                             maxXTicks=20,
                             obsMean=None,
                             obsUncertainty=None,
                             obsLegend=None,
                             legendLocation='lower left',
                             maxTitleLength=90):
    """
    Plots the list of time series data sets.

    Parameters
    ----------
    config : instance of ConfigParser
        the configuration, containing a [plot] section with options that
        control plotting

    dsvalues : list of xarray DataSets
        the data set(s) to be plotted

    title : str
        the title of the plot

    xlabel, ylabel : str
        axis labels

    calendar : str
        the calendar to use for formatting the time axis

    movingAveragePoints : int, optional
        the number of time points over which to perform a moving average

    lineColors, lineStyles, markers, legendText : list of str, optional
        control line color, style, marker, and corresponding legend
        text.  Default is black, solid line with no marker, and no legend.

    lineWidths : list of float, optional
        control line width.  Default is 1.0.

    maxPoints : list of {None, int}, optional
        the approximate maximum number of time points to use in a time series.
        This can be helpful for reducing the number of symbols plotted if
        plotting with markers.  Otherwise the markers become indistinguishable
        from each other.

    titleFontSize : int, optional
        the size of the title font

    figsize : tuple of float, optional
        the size of the figure in inches

    dpi : int, optional
        the number of dots per inch of the figure, taken from section ``plot``
        option ``dpi`` in the config file by default

    firstYearXTicks : int, optional
        The year of the first tick on the x axis.  By default, the first time
        entry is the first tick.

    yearStrideXTicks : int, optional
        The number of years between x ticks. By default, the stride is chosen
        automatically to have ``maxXTicks`` tick marks or fewer.

    maxXTicks : int, optional
        the maximum number of tick marks that will be allowed along the x axis.
        This may need to be adjusted depending on the figure size and aspect
        ratio.

    obsMean, obsUncertainty : list of float, optional
        Mean values and uncertainties for observations to be plotted as error
        bars. The two lists must have the same number of elements.

    obsLegend : list of str, optional
        The label in the legend for each element in ``obsMean`` (and
        ``obsUncertainty``)

    legendLocation : str, optional
        The location of the legend (see ``pyplot.legend()`` for details)

    maxTitleLength : int, optional
        the maximum number of characters in the title and legend, beyond which
        they are truncated with a trailing ellipsis

    Returns
    -------
    fig : ``matplotlib.figure.Figure``
        The resulting figure
    """
    # Authors
    # -------
    # Xylar Asay-Davis, Milena Veneziani, Stephen Price

    if dpi is None:
        dpi = config.getint('plot', 'dpi')
    fig = plt.figure(figsize=figsize, dpi=dpi)

    minDays = []
    maxDays = []
    labelCount = 0
    for dsIndex in range(len(dsvalues)):
        dsvalue = dsvalues[dsIndex]
        if dsvalue is None:
            continue
        if movingAveragePoints == 1 or movingAveragePoints is None:
            mean = dsvalue
        else:
            mean = pd.Series.rolling(dsvalue.to_pandas(),
                                     movingAveragePoints,
                                     center=True).mean()
            mean = xr.DataArray.from_series(mean)
        minDays.append(mean.Time.min())
        maxDays.append(mean.Time.max())

        if maxPoints is not None and maxPoints[dsIndex] is not None:
            nTime = mean.sizes['Time']
            if maxPoints[dsIndex] < nTime:
                stride = int(round(nTime / float(maxPoints[dsIndex])))
                mean = mean.isel(Time=slice(0, None, stride))

        if legendText is None:
            label = None
        else:
            label = legendText[dsIndex]
            if label is not None:
                label = limit_title(label, maxTitleLength)
            labelCount += 1
        if lineColors is None:
            color = 'k'
        else:
            color = lineColors[dsIndex]
        if lineStyles is None:
            linestyle = '-'
        else:
            linestyle = lineStyles[dsIndex]
        if markers is None:
            marker = None
        else:
            marker = markers[dsIndex]
        if lineWidths is None:
            linewidth = 1.
        else:
            linewidth = lineWidths[dsIndex]

        plt.plot(mean['Time'].values,
                 mean.values,
                 color=color,
                 linestyle=linestyle,
                 marker=marker,
                 linewidth=linewidth,
                 label=label)

    if obsMean is not None:
        obsCount = len(obsMean)
        assert (len(obsUncertainty) == obsCount)

        # space the observations along the time line, leaving gaps at either
        # end
        start = np.amin(minDays)
        end = np.amax(maxDays)
        obsTimes = np.linspace(start, end, obsCount + 2)[1:-1]
        obsSymbols = ['o', '^', 's', 'D', '*']
        obsColors = ['b', 'g', 'c', 'm', 'r']
        for iObs in range(obsCount):
            if obsMean[iObs] is not None:
                symbol = obsSymbols[np.mod(iObs, len(obsSymbols))]
                color = obsColors[np.mod(iObs, len(obsColors))]
                fmt = '{}{}'.format(color, symbol)
                plt.errorbar(obsTimes[iObs],
                             obsMean[iObs],
                             yerr=obsUncertainty[iObs],
                             fmt=fmt,
                             ecolor=color,
                             capsize=0,
                             label=obsLegend[iObs])
                # plot a box around the error bar to make it more visible
                boxHalfWidth = 0.01 * (end - start)
                boxHalfHeight = obsUncertainty[iObs]
                boxX = obsTimes[iObs] + \
                    boxHalfWidth * np.array([-1, 1, 1, -1, -1])
                boxY = obsMean[iObs] + \
                    boxHalfHeight * np.array([-1, -1, 1, 1, -1])

                plt.plot(boxX, boxY, '{}-'.format(color), linewidth=3)
                labelCount += 1

    if labelCount > 1:
        plt.legend(loc=legendLocation)

    ax = plt.gca()

    if titleFontSize is None:
        titleFontSize = config.get('plot', 'titleFontSize')
    axis_font = {'size': config.get('plot', 'axisFontSize')}
    title_font = {
        'size': titleFontSize,
        'color': config.get('plot', 'titleFontColor'),
        'weight': config.get('plot', 'titleFontWeight')
    }

    if firstYearXTicks is not None:
        minDays = date_to_days(year=firstYearXTicks, calendar=calendar)

    plot_xtick_format(calendar,
                      minDays,
                      maxDays,
                      maxXTicks,
                      yearStride=yearStrideXTicks)

    # Add a y=0 line if y ranges between positive and negative values
    yaxLimits = ax.get_ylim()
    if yaxLimits[0] * yaxLimits[1] < 0:
        x = ax.get_xlim()
        plt.plot(x, np.zeros(np.size(x)), 'k-', linewidth=1.2, zorder=1)

    if title is not None:
        title = limit_title(title, maxTitleLength)
        plt.title(title, **title_font)
    if xlabel is not None:
        plt.xlabel(xlabel, **axis_font)
    if ylabel is not None:
        plt.ylabel(ylabel, **axis_font)

    return fig
Exemple #2
0
def plot_vertical_section(
        config,
        xArray,
        depthArray,
        fieldArray,
        colorMapSectionName,
        suffix='',
        colorbarLabel=None,
        title=None,
        xlabel=None,
        ylabel=None,
        figsize=(10, 4),
        dpi=None,
        titleFontSize=None,
        titleY=None,
        axisFontSize=None,
        xLim=None,
        yLim=None,
        lineWidth=2,
        lineStyle='solid',
        lineColor='black',
        backgroundColor='grey',
        secondXAxisData=None,
        secondXAxisLabel=None,
        thirdXAxisData=None,
        thirdXAxisLabel=None,
        numUpperTicks=None,
        upperXAxisTickLabelPrecision=None,
        invertYAxis=True,
        xArrayIsTime=False,
        movingAveragePoints=None,
        firstYearXTicks=None,
        yearStrideXTicks=None,
        maxXTicks=20,
        calendar='gregorian',
        plotAsContours=False,
        contourComparisonFieldArray=None,
        comparisonFieldName=None,
        originalFieldName=None,
        comparisonContourLineStyle=None,
        comparisonContourLineColor=None,
        labelContours=False,
        contourLabelPrecision=1,
        maxTitleLength=70):  # {{{
    """
    Plots a data set as a x distance (latitude, longitude,
    or spherical distance) vs depth map (vertical section).

    Or, if xArrayIsTime is True, plots data set on a vertical
    Hovmoller plot (depth vs. time).

    Typically, the fieldArray data are plotted using a heatmap, but if
    contourComparisonFieldArray is not None, then contours of both
    fieldArray and contourComparisonFieldArray are plotted instead.

    Parameters
    ----------
    config : instance of ConfigParser
        the configuration, containing a [plot] section with options that
        control plotting

    xArray : float array
        x array (latitude, longitude, or spherical distance; or, time for a
        Hovmoller plot)

    depthArray : float array
        depth array [m]

    fieldArray : float array
        field array to plot

    colorMapSectionName : str
        section name in ``config`` where color map info can be found.

    suffix : str, optional
        the suffix used for colorbar config options

    colorbarLabel : str, optional
        the label for the colorbar.  If plotAsContours and labelContours are
        both True, colorbarLabel is used as follows (typically in order to
        indicate the units that are associated with the contour labels):
        if contourComparisonFieldArray is None, the colorbarLabel string is
        parenthetically appended to the plot title;  if
        contourComparisonFieldArray is not None, it is parenthetically appended
        to the legend entries of the contour comparison plot.

    title : str, optional
        title of plot

    xlabel, ylabel : str, optional
        label of x- and y-axis

    figsize : tuple of float, optional
        size of the figure in inches, or None if the current figure should
        be used (e.g. if this is a subplot)

    dpi : int, optional
        the number of dots per inch of the figure, taken from section ``plot``
        option ``dpi`` in the config file by default

    titleFontSize : int, optional
        size of the title font

    titleY : float, optional
        the y value to use for placing the plot title

    axisFontSize : int, optional
        size of the axis font

    xLim : float array, optional
        x range of plot

    yLim : float array, optional
        y range of plot

    lineWidth : int, optional
        the line width of contour lines (if specified)

    lineStyle : str, optional
        the line style of contour lines (if specified); this applies to the
        style of contour lines of fieldArray (the style of the contour lines
        of contourComparisonFieldArray is set using
        contourComparisonLineStyle).

    lineColor : str, optional
        the color of contour lines (if specified); this applies to the
        contour lines of fieldArray (the color of the contour lines of
        contourComparisonFieldArray is set using contourComparisonLineColor

    backgroundColor : str, optional
        the background color for the plot (NaNs will be shown in this color)

    secondXAxisData : the data to use to display a second x axis (which will be
        placed above the plot).  This array must have the same number of values
        as xArray, and it is assumed that the values in this array define
        locations along the x axis that are the same as those defined by the
        corresponding values in xArray, but in some different unit system.

    secondXAxisLabel : the label for the second x axis, if requested

    thirdXAxisData : the data to use to display a third x axis (which will be
        placed above the plot and above the second x axis, which must be
        specified if a third x axis is to be specified).  This array must have
        the same number of values as xArray, and it is assumed that the values
        in this array define locations along the x axis that are the same as
        those defined by the corresponding values in xArray, but in some
        different unit system (which is presumably also different from the unit
        system used for the values in the secondXAxisData array).  The typical
        use for this third axis is for transects, for which the primary x axis
        represents distance along a transect, and the second and third x axes
        are used to display the corresponding latitudes and longitudes.

    thirdXAxisLabel : the label for the third x axis, if requested

    numUpperTicks : the approximate number of ticks to use on the upper x axis
        or axes (these are the second and third x axes, which are placed above
        the plot if they have been requested by specifying the secondXAxisData
        or thirdXAxisData arrays above)

    upperXAxisTickLabelPrecision : the number of decimal places (to the right
        of the decimal point) to use for values at upper axis ticks.  This
        value can be adjusted (in concert with numUpperTicks) to avoid problems
        with overlapping numbers along the upper axis.

    invertYAxis : logical, optional
        if True, invert Y axis

    xArrayIsTime : logical, optional
        if True, format the x axis for time (this applies only to the primary
        x axis, not to the optional second or third x axes)

    movingAveragePoints : int, optional
        the number of points over which to perform a moving average
        NOTE: this option is mostly intended for use when xArrayIsTime is True,
        although it will work with other data as well.  Also, the moving
        average calculation is based on number of points, not actual x axis
        values, so for best results, the values in the xArray should be equally
        spaced.

    firstYearXTicks : int, optional
        The year of the first tick on the x axis.  By default, the first time
        entry is the first tick.

    yearStrideXTicks : int, optional
        The number of years between x ticks. By default, the stride is chosen
        automatically to have ``maxXTicks`` tick marks or fewer.

    maxXTicks : int, optional
        the maximum number of tick marks that will be allowed along the primary
        x axis.  This may need to be adjusted depending on the figure size and
        aspect ratio.  NOTE:  maxXTicks is only used if xArrayIsTime is True

    calendar : str, optional
        the calendar to use for formatting the time axis
        NOTE:  calendar is only used if xArrayIsTime is True

    plotAsContours : bool, optional
        if plotAsContours is True, instead of plotting fieldArray as a
        heatmap, the function will plot only the contours of fieldArray.  In
        addition, if contourComparisonFieldArray is not None, the contours
        of this field will be plotted on the same plot.  The selection of
        contour levels is still determined as for the contours on the heatmap
        plots, via the 'contours' entry in colorMapSectionName.

    contourComparisonFieldArray : float array, optional
        a comparison field array (typically observational data or results from
        another simulation run), assumed to be of the same shape as fieldArray,
        and related to xArray and depthArray in the same way fieldArray is.
        If contourComparisonFieldArray is None, then fieldArray will be plotted
        as a heatmap.  However, if countourComparisonFieldArray is not None,
        then contours of both fieldArray and contourComparisonFieldArray will
        be plotted in order to enable a comparison of the two fields on the
        same plot.  If plotAsContours is False, this parameter is ignored.

    comparisonFieldName : str, optional
       the name for the comparison field.  If contourComparisonFieldArray is
       None, this parameter is ignored.

    originalFieldName : str, optional
       the name for the fieldArray field (for the purposes of labeling the
       contours on a contour comparison plot).  If contourComparisonFieldArray
       is None, this parameter is ignored.

    comparisonContourLineStyle : str, optional
        the line style of contour lines of the comparisonFieldName field on
        a contour comparison plot

    comparisonContourLineColor : str, optional
        the line color of contour lines of the comparisonFieldName field on
        a contour comparison plot

    labelContours : bool, optional
        whether or not to label contour lines (if specified) with their values

    contourLabelPrecision : int, optional
        the precision (in terms of number of figures to the right of the
        decimal point) of contour labels

    maxTitleLength : int, optional
        the maximum number of characters in the title, beyond which it is
        truncated with a trailing ellipsis

    Returns
    -------
    fig : ``matplotlib.figure.Figure``
        The figure that was plotted

    ax : ``matplotlib.axes.Axes``
        The subplot
    """
    # Authors
    # -------
    # Milena Veneziani, Mark Petersen, Xylar Asay-Davis, Greg Streletz

    # compute moving averages with respect to the x dimension
    if movingAveragePoints is not None and movingAveragePoints != 1:
        N = movingAveragePoints
        movingAverageDepthSlices = []
        for nVertLevel in range(len(depthArray)):
            depthSlice = fieldArray[[nVertLevel]][0]
            # in case it's not an xarray already
            depthSlice = xr.DataArray(depthSlice)
            mean = pd.Series.rolling(depthSlice.to_series(), N,
                                     center=True).mean()
            mean = xr.DataArray.from_series(mean)
            mean = mean[int(N / 2.0):-int(round(N / 2.0) - 1)]
            movingAverageDepthSlices.append(mean)
        xArray = xArray[int(N / 2.0):-int(round(N / 2.0) - 1)]
        fieldArray = xr.DataArray(movingAverageDepthSlices)

    dimX = xArray.shape
    dimZ = depthArray.shape
    dimF = fieldArray.shape
    if contourComparisonFieldArray is not None:
        dimC = contourComparisonFieldArray.shape

    if len(dimX) != 1 and len(dimX) != 2:
        raise ValueError('xArray must have either one or two dimensions '
                         '(has %d)' % dimX)

    if len(dimZ) != 1 and len(dimZ) != 2:
        raise ValueError('depthArray must have either one or two dimensions '
                         '(has %d)' % dimZ)

    if len(dimF) != 2:
        raise ValueError('fieldArray must have two dimensions (has %d)' % dimF)

    if contourComparisonFieldArray is not None:
        if len(dimC) != 2:
            raise ValueError('contourComparisonFieldArray must have two '
                             'dimensions (has %d)' % dimC)
        elif (fieldArray.shape[0] != contourComparisonFieldArray.shape[0]) or \
             (fieldArray.shape[1] != contourComparisonFieldArray.shape[1]):
            raise ValueError('size mismatch between fieldArray (%d x %d) and '
                             'contourComparisonFieldArray (%d x %d)' %
                             (fieldArray.shape[0], fieldArray.shape[1],
                              contourComparisonFieldArray.shape[0],
                              contourComparisonFieldArray.shape[1]))

    # verify that the dimensions of fieldArray are consistent with those of
    # xArray and depthArray
    if len(dimX) == 1 and len(dimZ) == 1:
        num_x = dimX[0]
        num_z = dimZ[0]
        if num_x != fieldArray.shape[1] or num_z != fieldArray.shape[0]:
            raise ValueError('size mismatch between xArray (%d), '
                             'depthArray (%d), and fieldArray (%d x %d)' %
                             (num_x, num_z, fieldArray.shape[0],
                              fieldArray.shape[1]))
    elif len(dimX) == 1:
        num_x = dimX[0]
        num_x_Z = dimZ[1]
        num_z = dimZ[0]
        if num_x != fieldArray.shape[1] or num_z != fieldArray.shape[0] or \
                num_x != num_x_Z:
            raise ValueError('size mismatch between xArray (%d), '
                             'depthArray (%d x %d), and fieldArray (%d x %d)' %
                             (num_x, num_z, num_x_Z,
                              fieldArray.shape[0],
                              fieldArray.shape[1]))
    elif len(dimZ) == 1:
        num_x = dimX[1]
        num_z_X = dimX[0]
        num_z = dimZ[0]
        if num_x != fieldArray.shape[1] or num_z != fieldArray.shape[0] or \
                num_z != num_z_X:
            raise ValueError('size mismatch between xArray (%d x %d), '
                             'depthArray (%d), and fieldArray (%d x %d)' %
                             (num_z_X, num_x, num_z,
                              fieldArray.shape[0],
                              fieldArray.shape[1]))
    else:
        num_x = dimX[1]
        num_z_X = dimX[0]
        num_x_Z = dimZ[1]
        num_z = dimZ[0]
        if num_x != fieldArray.shape[1] or num_z != fieldArray.shape[0] \
                or num_x != num_x_Z or num_z != num_z_X:
            raise ValueError('size mismatch between xArray (%d x %d), '
                             'depthArray (%d x %d), and fieldArray (%d x %d)' %
                             (num_z_X, num_x, num_z, num_x_Z,
                              fieldArray.shape[0],
                              fieldArray.shape[1]))

    # Verify that the upper x-axis parameters are consistent with each other
    # and with xArray
    if secondXAxisData is None and thirdXAxisData is not None:
        raise ValueError('secondXAxisData cannot be None if thirdXAxisData '
                         'is not None')
    if secondXAxisData is not None:
        arrayShape = secondXAxisData.shape
        if len(arrayShape) == 1 and arrayShape[0] != num_x:
            raise ValueError('secondXAxisData has %d x values, '
                             'but should have num_x = %d x values' %
                             (arrayShape[0], num_x))
        elif len(arrayShape) == 2 and arrayShape[1] != num_x:
            raise ValueError('secondXAxisData has %d x values, '
                             'but should have num_x = %d x values' %
                             (arrayShape[1], num_x))
        elif len(arrayShape) > 2:
            raise ValueError('secondXAxisData must be a 1D or 2D array, '
                             'but is of dimension %d' %
                             (len(arrayShape)))
    if thirdXAxisData is not None:
        arrayShape = thirdXAxisData.shape
        if len(arrayShape) == 1 and arrayShape[0] != num_x:
            raise ValueError('thirdXAxisData has %d x values, '
                             'but should have num_x = %d x values' %
                             (arrayShape[0], num_x))
        elif len(arrayShape) == 2 and arrayShape[1] != num_x:
            raise ValueError('thirdXAxisData has %d x values, '
                             'but should have num_x = %d x values' %
                             (arrayShape[1], num_x))
        elif len(arrayShape) > 2:
            raise ValueError('thirdXAxisData must be a 1D or 2D array, '
                             'but is of dimension %d' %
                             (len(arrayShape)))

    # define x and y as the appropriate 2D arrays for plotting
    if len(dimX) == 1 and len(dimZ) == 1:
        x, y = np.meshgrid(xArray, depthArray)
    elif len(dimX) == 1:
        x, y = np.meshgrid(xArray, np.zeros(num_z))
        y = depthArray
    elif len(dimZ) == 1:
        x, y = np.meshgrid(np.zeros(num_x), depthArray)
        x = xArray
    else:
        x = xArray
        y = depthArray

    # set up figure
    if dpi is None:
        dpi = config.getint('plot', 'dpi')
    if figsize is not None:
        fig = plt.figure(figsize=figsize, dpi=dpi)
    else:
        fig = plt.gcf()

    colormapDict = setup_colormap(config, colorMapSectionName, suffix=suffix)

    if not plotAsContours:    # display a heatmap of fieldArray

        if colormapDict['levels'] is None:
            # interpFieldArray contains the values at centers of grid cells,
            # for pcolormesh plots (using bilinear interpolation)
            interpFieldArray = \
                0.5 * (0.5 * (fieldArray[1:, 1:] + fieldArray[0:-1, 1:]) +
                       0.5 * (fieldArray[1:, 0:-1] + fieldArray[0:-1, 0:-1]))

            plotHandle = plt.pcolormesh(x, y, interpFieldArray,
                                        cmap=colormapDict['colormap'],
                                        norm=colormapDict['norm'])
        else:
            plotHandle = plt.contourf(x, y, fieldArray,
                                      cmap=colormapDict['colormap'],
                                      norm=colormapDict['norm'],
                                      levels=colormapDict['levels'],
                                      extend='both')

        cbar = plt.colorbar(plotHandle,
                            orientation='vertical',
                            spacing='uniform',
                            aspect=9,
                            ticks=colormapDict['ticks'],
                            boundaries=colormapDict['ticks'])

        if colorbarLabel is not None:
            cbar.set_label(colorbarLabel)

    else:     # display a white heatmap to get a white background for non-land
        zeroArray = np.ma.where(fieldArray != np.nan, 0.0, fieldArray)
        plt.contourf(x, y, zeroArray, colors='white')

    # set the color for NaN or masked regions, and draw a black
    # outline around them; technically, the contour level used should
    # be 1.0, but the contours don't show up when using 1.0, so 0.999
    # is used instead
    ax = plt.gca()
    ax.set_facecolor(backgroundColor)
    landArray = np.ma.where(fieldArray != np.nan, 1.0, fieldArray)
    landArray = np.ma.masked_where(landArray == np.nan, landArray, copy=True)
    landArray = landArray.filled(0.0)
    plt.contour(x, y, landArray, levels=[0.999], colors='black', linewidths=1)

    # plot contours, if they were requested
    contourLevels = colormapDict['contours']
    if contourLevels is not None:
        if len(contourLevels) == 0:
            # automatic calculation of contour levels
            contourLevels = None
        cs1 = plt.contour(x, y, fieldArray,
                          levels=contourLevels,
                          colors=lineColor,
                          linestyles=lineStyle,
                          linewidths=lineWidth)
        if labelContours:
            fmt_string = "%%1.%df" % int(contourLabelPrecision)
            plt.clabel(cs1, fmt=fmt_string)
        if plotAsContours and contourComparisonFieldArray is not None:
            cs2 = plt.contour(x, y, contourComparisonFieldArray,
                              levels=contourLevels,
                              colors=comparisonContourLineColor,
                              linestyles=comparisonContourLineStyle,
                              linewidths=lineWidth)
            if labelContours:
                plt.clabel(cs2, fmt=fmt_string)

    if plotAsContours and contourComparisonFieldArray is not None:
        h1, _ = cs1.legend_elements()
        h2, _ = cs2.legend_elements()
        if labelContours:
            originalFieldName = originalFieldName + " (" + colorbarLabel + ")"
            comparisonFieldName = comparisonFieldName + " (" + \
                colorbarLabel + ")"
        ax.legend([h1[0], h2[0]], [originalFieldName, comparisonFieldName],
                  loc='upper center', bbox_to_anchor=(0.5, -0.25), ncol=1)

    if title is not None:
        if plotAsContours and labelContours \
           and contourComparisonFieldArray is None:
            title = limit_title(title, maxTitleLength-(3+len(colorbarLabel)))
            title = title + " (" + colorbarLabel + ")"
        else:
            title = limit_title(title, maxTitleLength)
        if titleFontSize is None:
            titleFontSize = config.get('plot', 'titleFontSize')
        title_font = {'size': titleFontSize,
                      'color': config.get('plot', 'titleFontColor'),
                      'weight': config.get('plot', 'titleFontWeight')}
        if titleY is not None:
            plt.title(title, y=titleY, **title_font)
        else:
            plt.title(title, **title_font)

    if (xlabel is not None) or (ylabel is not None):
        if axisFontSize is None:
            axisFontSize = config.get('plot', 'axisFontSize')
        axis_font = {'size': axisFontSize}

    if xlabel is not None:
        plt.xlabel(xlabel, **axis_font)
    if ylabel is not None:
        plt.ylabel(ylabel, **axis_font)

    if invertYAxis:
        ax.invert_yaxis()

    if xLim:
        ax.set_xlim(xLim)
    if yLim:
        ax.set_ylim(yLim)

    if xArrayIsTime:
        if firstYearXTicks is None:
            minDays = [xArray[0]]
        else:
            minDays = date_to_days(year=firstYearXTicks, calendar=calendar)
        maxDays = [xArray[-1]]

        plot_xtick_format(calendar, minDays, maxDays, maxXTicks,
                          yearStride=yearStrideXTicks)

    # add a second x-axis scale, if it was requested
    if secondXAxisData is not None:
        ax2 = ax.twiny()
        ax2.set_facecolor(backgroundColor)
        ax2.set_xlabel(secondXAxisLabel, **axis_font)
        xlimits = ax.get_xlim()
        ax2.set_xlim(xlimits)
        xticks = np.linspace(xlimits[0], xlimits[1], numUpperTicks)
        tickValues = np.interp(xticks, x.flatten()[:num_x], secondXAxisData)
        ax2.set_xticks(xticks)
        formatString = "{{0:.{:d}f}}{}".format(
            upperXAxisTickLabelPrecision, r'$\degree$')
        ax2.set_xticklabels([formatString.format(member)
                             for member in tickValues])

        # add a third x-axis scale, if it was requested
        if thirdXAxisData is not None:
            ax3 = ax.twiny()
            ax3.set_facecolor(backgroundColor)
            ax3.set_xlabel(thirdXAxisLabel, **axis_font)
            ax3.set_xlim(xlimits)
            ax3.set_xticks(xticks)
            tickValues = np.interp(xticks, x.flatten()[:num_x], thirdXAxisData)
            ax3.set_xticklabels([formatString.format(member)
                                 for member in tickValues])
            ax3.spines['top'].set_position(('outward', 36))

    return fig, ax  # }}}
Exemple #3
0
def timeseries_analysis_plot_polar(config,
                                   dsvalues,
                                   title,
                                   movingAveragePoints=None,
                                   lineColors=None,
                                   lineStyles=None,
                                   markers=None,
                                   lineWidths=None,
                                   legendText=None,
                                   titleFontSize=None,
                                   figsize=(15, 6),
                                   dpi=None,
                                   maxTitleLength=90):
    """
    Plots the list of time series data sets on a polar plot.

    Parameters
    ----------
    config : instance of ConfigParser
        the configuration, containing a [plot] section with options that
        control plotting

    dsvalues : list of xarray DataSets
        the data set(s) to be plotted

    movingAveragePoints : int
        the numer of time points over which to perform a moving average

    title : str
        the title of the plot

    lineColors, lineStyles, markers, legendText : list of str, optional
        control line color, style, marker, and corresponding legend
        text.  Default is black, solid line with no marker, and no legend.

    lineWidths : list of float, optional
        control line width.  Default is 1.0.

    titleFontSize : int, optional
        the size of the title font

    figsize : tuple of float, optional
        the size of the figure in inches

    dpi : int, optional
        the number of dots per inch of the figure, taken from section ``plot``
        option ``dpi`` in the config file by default

    maxTitleLength : int, optional
        the maximum number of characters in the title and legend, beyond which
        they are truncated with a trailing ellipsis

    Returns
    -------
    fig : ``matplotlib.figure.Figure``
        The resulting figure
    """
    # Authors
    # -------
    # Adrian K. Turner, Xylar Asay-Davis

    if dpi is None:
        dpi = config.getint('plot', 'dpi')
    fig = plt.figure(figsize=figsize, dpi=dpi)

    minDays = []
    maxDays = []
    labelCount = 0
    for dsIndex in range(len(dsvalues)):
        dsvalue = dsvalues[dsIndex]
        if dsvalue is None:
            continue
        mean = pd.Series.rolling(dsvalue.to_pandas(),
                                 movingAveragePoints,
                                 center=True).mean()
        mean = xr.DataArray.from_series(mean)
        minDays.append(mean.Time.min())
        maxDays.append(mean.Time.max())

        if legendText is None:
            label = None
        else:
            label = legendText[dsIndex]
            if label is not None:
                label = limit_title(label, maxTitleLength)
            labelCount += 1
        if lineColors is None:
            color = 'k'
        else:
            color = lineColors[dsIndex]
        if lineStyles is None:
            linestyle = '-'
        else:
            linestyle = lineStyles[dsIndex]
        if markers is None:
            marker = None
        else:
            marker = markers[dsIndex]
        if lineWidths is None:
            linewidth = 1.
        else:
            linewidth = lineWidths[dsIndex]

        plt.polar((mean['Time'] / 365.0) * np.pi * 2.0,
                  mean,
                  color=color,
                  linestyle=linestyle,
                  marker=marker,
                  linewidth=linewidth,
                  label=label)

    if labelCount > 1:
        plt.legend(loc='lower left')

    ax = plt.gca()

    # set azimuthal axis formatting
    majorTickLocs = np.zeros(12)
    minorTickLocs = np.zeros(12)
    majorTickLocs[0] = 0.0
    minorTickLocs[0] = (constants.daysInMonth[0] * np.pi) / 365.0
    for month in range(1, 12):
        majorTickLocs[month] = majorTickLocs[month - 1] + \
            ((constants.daysInMonth[month - 1] * np.pi * 2.0) / 365.0)
        minorTickLocs[month] = minorTickLocs[month - 1] + \
            (((constants.daysInMonth[month - 1] +
               constants.daysInMonth[month]) * np.pi) / 365.0)

    ax.set_xticks(majorTickLocs)
    ax.set_xticklabels([])

    ax.set_xticks(minorTickLocs, minor=True)
    ax.set_xticklabels(constants.abrevMonthNames, minor=True)

    if titleFontSize is None:
        title = limit_title(title, maxTitleLength)
        titleFontSize = config.get('plot', 'titleFontSize')

    title_font = {
        'size': titleFontSize,
        'color': config.get('plot', 'titleFontColor'),
        'weight': config.get('plot', 'titleFontWeight')
    }
    if title is not None:
        plt.title(title, **title_font)

    return fig
Exemple #4
0
def plot_1D(config,
            xArrays,
            fieldArrays,
            errArrays,
            lineColors=None,
            lineStyles=None,
            markers=None,
            lineWidths=None,
            legendText=None,
            title=None,
            xlabel=None,
            ylabel=None,
            fileout='plot_1D.png',
            figsize=(10, 4),
            dpi=None,
            xLim=None,
            yLim=None,
            invertYAxis=False,
            maxTitleLength=80):  # {{{
    """
    Plots a 1D line plot with error bars if available.

    Parameters
    ----------
    config : instance of ConfigParser
        the configuration, containing a [plot] section with options that
        control plotting

    xArrays : list of float arrays
        x array (latitude, or any other x axis except time)

    fieldArrays : list of float arrays
        y array (any field as function of x)

    errArrays : list of float arrays
        error array (y errors)

    lineColors, lineStyles, markers, legendText : list of str, optional
        control line color, style, marker, and corresponding legend
        text.  Default is black, solid line with no marker, and no legend.

    lineWidths : list of float, optional
        control line width.  Default is 1.0.

    title : str, optional
        title of plot

    xlabel, ylabel : str, optional
        label of x- and y-axis

    fileout : str, optional
        the file name to be written

    figsize : tuple of float, optional
        size of the figure in inches

    dpi : int, optional
        the number of dots per inch of the figure, taken from section ``plot``
        option ``dpi`` in the config file by default

    xLim : float array, optional
        x range of plot

    yLim : float array, optional
        y range of plot

    invertYAxis : logical, optional
        if True, invert Y axis

    maxTitleLength : int, optional
        the maximum number of characters in the title and legend, beyond which
        they are truncated with a trailing ellipsis
    """
    # Authors
    # -------
    # Mark Petersen, Milena Veneziani

    # set up figure
    if dpi is None:
        dpi = config.getint('plot', 'dpi')
    plt.figure(figsize=figsize, dpi=dpi)

    plotLegend = False
    for dsIndex in range(len(xArrays)):
        xArray = xArrays[dsIndex]
        fieldArray = fieldArrays[dsIndex]
        errArray = errArrays[dsIndex]
        if xArray is None:
            continue

        if legendText is None:
            label = None
        else:
            label = legendText[dsIndex]
            if label is not None:
                label = limit_title(label, maxTitleLength)
            plotLegend = True
        if lineColors is None:
            color = 'k'
        else:
            color = lineColors[dsIndex]
        if markers is None:
            marker = None
        else:
            marker = markers[dsIndex]
        if lineStyles is None:
            linestyle = '-'
        else:
            linestyle = lineStyles[dsIndex]
        if lineWidths is None:
            linewidth = 1.
        else:
            linewidth = lineWidths[dsIndex]

        plt.plot(xArray,
                 fieldArray,
                 color=color,
                 linestyle=linestyle,
                 marker=marker,
                 linewidth=linewidth,
                 label=label)
        if errArray is not None:
            plt.fill_between(xArray,
                             fieldArray,
                             fieldArray + errArray,
                             facecolor=color,
                             alpha=0.2)
            plt.fill_between(xArray,
                             fieldArray,
                             fieldArray - errArray,
                             facecolor=color,
                             alpha=0.2)
    plt.grid()
    plt.axhline(0.0, linestyle='-', color='k')  # horizontal lines
    if plotLegend and len(xArrays) > 1:
        plt.legend()

    axis_font = {'size': config.get('plot', 'axisFontSize')}
    title_font = {
        'size': config.get('plot', 'titleFontSize'),
        'color': config.get('plot', 'titleFontColor'),
        'weight': config.get('plot', 'titleFontWeight')
    }
    if title is not None:
        title = limit_title(title, max_title_length=maxTitleLength)
        plt.title(title, **title_font)
    if xlabel is not None:
        plt.xlabel(xlabel, **axis_font)
    if ylabel is not None:
        plt.ylabel(ylabel, **axis_font)

    if invertYAxis:
        plt.gca().invert_yaxis()

    if xLim:
        plt.xlim(xLim)
    if yLim:
        plt.ylim(yLim)

    if fileout is not None:
        plt.savefig(fileout, dpi=dpi, bbox_inches='tight', pad_inches=0.1)

    plt.close()  # }}}
Exemple #5
0
    def run_task(self):  # {{{
        """
        Plots time-series output of properties in an ocean region.
        """
        # Authors
        # -------
        # Xylar Asay-Davis

        self.logger.info("\nPlotting TS diagram for {}"
                         "...".format(self.regionName))

        register_custom_colormaps()

        config = self.config
        sectionName = self.sectionName

        startYear = self.mpasClimatologyTask.startYear
        endYear = self.mpasClimatologyTask.endYear

        regionMaskFile = self.mpasMasksSubtask.geojsonFileName

        fcAll = read_feature_collection(regionMaskFile)

        fc = FeatureCollection()
        for feature in fcAll.features:
            if feature['properties']['name'] == self.regionName:
                fc.add_feature(feature)
                break

        self.logger.info('  Make plots...')

        groupLink = 'tsDiag' + self.regionGroup[0].lower() + \
            self.regionGroup[1:].replace(' ', '')

        nSubplots = 1 + len(self.obsDicts)
        if self.controlConfig is not None:
            nSubplots += 1

        if nSubplots == 4:
            nCols = 2
            nRows = 2
        else:
            nCols = min(nSubplots, 3)
            nRows = (nSubplots - 1) // 3 + 1

        axisIndices = numpy.reshape(numpy.arange(nRows * nCols),
                                    (nRows, nCols))[::-1, :].ravel()

        titleFontSize = config.get('plot', 'titleFontSize')
        axis_font = {'size': config.get('plot', 'axisFontSize')}
        title_font = {
            'size': titleFontSize,
            'color': config.get('plot', 'titleFontColor'),
            'weight': config.get('plot', 'titleFontWeight')
        }

        width = 3 + 4.5 * nCols
        height = 2 + 4 * nRows

        # noinspection PyTypeChecker
        fig, axarray = plt.subplots(nrows=nRows,
                                    ncols=nCols,
                                    sharey=True,
                                    figsize=(width, height))

        if nSubplots == 1:
            axarray = numpy.array(axarray)

        if nRows == 1:
            axarray = axarray.reshape((nRows, nCols))

        T, S, zMid, volume, zmin, zmax = self._get_mpas_t_s(self.config)
        mainRunName = config.get('runs', 'mainRunName')
        plotFields = [{
            'S': S,
            'T': T,
            'z': zMid,
            'vol': volume,
            'title': mainRunName
        }]

        if self.controlConfig is not None:
            T, S, zMid, volume, _, _ = self._get_mpas_t_s(self.controlConfig)
            controlRunName = self.controlConfig.get('runs', 'mainRunName')
            plotFields.append({
                'S': S,
                'T': T,
                'z': zMid,
                'vol': volume,
                'title': 'Control: {}'.format(controlRunName)
            })

        for obsName in self.obsDicts:
            obsT, obsS, obsZ, obsVol = self._get_obs_t_s(
                self.obsDicts[obsName])
            plotFields.append({
                'S': obsS,
                'T': obsT,
                'z': obsZ,
                'vol': obsVol,
                'title': obsName
            })

        Tbins = config.getExpression(sectionName, 'Tbins', usenumpyfunc=True)
        Sbins = config.getExpression(sectionName, 'Sbins', usenumpyfunc=True)

        normType = config.get(sectionName, 'normType')

        PT, SP = numpy.meshgrid(Tbins, Sbins)
        SA = gsw.SA_from_SP(SP, p=0., lon=0., lat=-75.)
        CT = gsw.CT_from_t(SA, PT, p=0.)

        neutralDensity = sigma0(SA, CT)
        rhoInterval = config.getfloat(sectionName, 'rhoInterval')
        contours = numpy.arange(24., 29. + rhoInterval, rhoInterval)

        diagramType = config.get(sectionName, 'diagramType')
        if diagramType not in ['volumetric', 'scatter']:
            raise ValueError('Unexpected diagramType {}'.format(diagramType))

        lastPanel = None
        if config.has_option(sectionName, 'volMin'):
            volMinMpas = config.getfloat(sectionName, 'volMin')
        else:
            volMinMpas = None
        if config.has_option(sectionName, 'volMax'):
            volMaxMpas = config.getfloat(sectionName, 'volMax')
        else:
            volMaxMpas = None
        for index in range(len(axisIndices)):
            panelIndex = axisIndices[index]

            row = nRows - 1 - index // nCols
            col = numpy.mod(index, nCols)

            if panelIndex >= nSubplots:
                plt.delaxes(axarray[row, col])
                continue

            plt.sca(axarray[row, col])
            T = plotFields[index]['T']
            S = plotFields[index]['S']
            z = plotFields[index]['z']
            volume = plotFields[index]['vol']
            title = plotFields[index]['title']
            title = limit_title(title, max_title_length=60)

            CS = plt.contour(SP,
                             PT,
                             neutralDensity,
                             contours,
                             linewidths=1.,
                             colors='k',
                             zorder=2)
            plt.clabel(CS, fontsize=12, inline=1, fmt='%4.2f')

            if diagramType == 'volumetric':
                lastPanel, volMin, volMax = \
                    self._plot_volumetric_panel(T, S, volume)

                if volMinMpas is None:
                    volMinMpas = volMin
                if volMaxMpas is None:
                    volMaxMpas = volMax
                if normType == 'linear':
                    norm = colors.Normalize(vmin=0., vmax=volMaxMpas)
                elif normType == 'log':
                    if volMinMpas is None or volMaxMpas is None:
                        norm = None
                    else:
                        norm = colors.LogNorm(vmin=volMinMpas, vmax=volMaxMpas)
                else:
                    raise ValueError(
                        'Unsupported normType {}'.format(normType))
                if norm is not None:
                    lastPanel.set_norm(norm)
            else:
                lastPanel = self._plot_scatter_panel(T, S, z, zmin, zmax)

            CTFreezing = freezing.CT_freezing(Sbins, 0, 1)
            PTFreezing = gsw.t_from_CT(gsw.SA_from_SP(Sbins,
                                                      p=0.,
                                                      lon=0.,
                                                      lat=-75.),
                                       CTFreezing,
                                       p=0.)
            plt.plot(Sbins,
                     PTFreezing,
                     linestyle='--',
                     linewidth=1.,
                     color='k')

            plt.ylim([Tbins[0], Tbins[-1]])
            plt.xlim([Sbins[0], Sbins[-1]])

            plt.xlabel('Salinity (PSU)', **axis_font)
            if col == 0:
                plt.ylabel(r'Potential temperature ($^\circ$C)', **axis_font)
            plt.title(title)

        # do this before the inset because otherwise it moves the inset
        # and cartopy doesn't play too well with tight_layout anyway
        plt.tight_layout()

        fig.subplots_adjust(right=0.91)
        if nRows == 1:
            fig.subplots_adjust(top=0.85)
        else:
            fig.subplots_adjust(top=0.88)

        suptitle = 'T-S diagram for {} ({}, {:04d}-{:04d})\n' \
                   ' {} m < z < {} m'.format(self.regionName, self.season,
                                             startYear, endYear, zmin, zmax)
        fig.text(0.5,
                 0.9,
                 suptitle,
                 horizontalalignment='center',
                 **title_font)

        inset = add_inset(fig, fc, width=1.5, height=1.5)

        # add an empty plot covering the subplots to give common axis labels
        pos0 = axarray[0, 0].get_position()
        pos1 = axarray[-1, -1].get_position()
        pos_common = [pos0.x0, pos1.y0, pos1.x1 - pos0.x0, pos0.y1 - pos1.y0]
        print(pos_common)
        common_ax = fig.add_axes(pos_common, zorder=-2)
        common_ax.spines['top'].set_color('none')
        common_ax.spines['bottom'].set_color('none')
        common_ax.spines['left'].set_color('none')
        common_ax.spines['right'].set_color('none')
        common_ax.tick_params(labelcolor='w',
                              top=False,
                              bottom=False,
                              left=False,
                              right=False)

        common_ax.set_xlabel('Salinity (PSU)', **axis_font)
        common_ax.set_ylabel(r'Potential temperature ($^\circ$C)', **axis_font)

        # turn off labels for individual plots (just used for spacing)
        for index in range(len(axisIndices)):
            row = nRows - 1 - index // nCols
            col = numpy.mod(index, nCols)
            ax = axarray[row, col]
            ax.set_xlabel('')
            ax.set_ylabel('')

        # move the color bar down a little ot avoid the inset
        pos0 = inset.get_position()
        pos1 = axarray[-1, -1].get_position()
        pad = 0.04
        top = pos0.y0 - pad
        height = top - pos1.y0
        cbar_ax = fig.add_axes([0.92, pos1.y0, 0.02, height])
        cbar = fig.colorbar(lastPanel, cax=cbar_ax)

        if diagramType == 'volumetric':
            cbar.ax.get_yaxis().labelpad = 15
            cbar.ax.set_ylabel(r'volume (m$^3$)', rotation=270)
        else:
            cbar.ax.set_ylabel('depth (m)', rotation=270)

        outFileName = '{}/TS_diagram_{}_{}.png'.format(self.plotsDirectory,
                                                       self.prefix,
                                                       self.season)
        savefig(outFileName, tight=False)

        caption = 'Regional mean of {}'.format(suptitle)
        write_image_xml(config=config,
                        filePrefix='TS_diagram_{}_{}'.format(
                            self.prefix, self.season),
                        componentName='Ocean',
                        componentSubdirectory='ocean',
                        galleryGroup='T-S Diagrams',
                        groupLink=groupLink,
                        gallery=self.regionGroup,
                        thumbnailDescription=self.regionName,
                        imageDescription=caption,
                        imageCaption=caption)
    def plot_panel(ax, title, array, colormap, norm, levels, ticks, contours,
                   lineWidth, lineColor):

        title = limit_title(title, maxTitleLength)
        ax.set_title(title, y=1.06, **plottitle_font)

        ax.set_extent(extent, crs=projection)

        gl = ax.gridlines(crs=cartopy.crs.PlateCarree(),
                          color='k',
                          linestyle=':',
                          zorder=5,
                          draw_labels=True)
        gl.xlocator = mticker.FixedLocator(np.arange(-180., 181., 60.))
        gl.ylocator = mticker.FixedLocator(np.arange(-80., 81., 10.))
        gl.n_steps = 100
        gl.right_labels = False
        gl.xformatter = cartopy.mpl.gridliner.LONGITUDE_FORMATTER
        gl.yformatter = cartopy.mpl.gridliner.LATITUDE_FORMATTER

        if levels is None:
            plotHandle = ax.pcolormesh(x, y, array, cmap=colormap, norm=norm)
        else:
            plotHandle = ax.contourf(xCenter,
                                     yCenter,
                                     array,
                                     cmap=colormap,
                                     norm=norm,
                                     levels=levels,
                                     extend='both')

        if useCartopyCoastline:
            _add_land_lakes_coastline(ax, ice_shelves=False)
        else:
            # add the model coastline
            plt.pcolormesh(x, y, landMask, cmap=landColorMap)
            plt.contour(xCenter,
                        yCenter,
                        landMask.mask, (0.5, ),
                        colors='k',
                        linewidths=0.5)

        if contours is not None:
            matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
            ax.contour(x,
                       y,
                       array,
                       levels=contours,
                       colors=lineColor,
                       linewidths=lineWidth)

        # create an axes on the right side of ax. The width of cax will be 5%
        # of ax and the padding between cax and ax will be fixed at 0.05 inch.
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right",
                                  size="5%",
                                  pad=0.05,
                                  axes_class=plt.Axes)

        cbar = plt.colorbar(plotHandle, cax=cax)
        cbar.set_label(cbarlabel)
        if ticks is not None:
            cbar.set_ticks(ticks)
            cbar.set_ticklabels(['{}'.format(tick) for tick in ticks])
    def plot_panel(ax, title, array, colormap, norm, levels, ticks, contours,
                   lineWidth, lineColor):

        ax.set_extent(extent, crs=projection)

        title = limit_title(title, maxTitleLength)
        ax.set_title(title, y=1.02, **plottitle_font)

        gl = ax.gridlines(crs=projection,
                          color='k',
                          linestyle=':',
                          zorder=5,
                          draw_labels=True)
        gl.right_labels = False
        gl.top_labels = False
        gl.xlocator = mticker.FixedLocator(np.arange(-180., 181., 60.))
        gl.ylocator = mticker.FixedLocator(np.arange(-80., 81., 20.))
        gl.xformatter = cartopy.mpl.gridliner.LONGITUDE_FORMATTER
        gl.yformatter = cartopy.mpl.gridliner.LATITUDE_FORMATTER

        if levels is None:
            plotHandle = ax.pcolormesh(Lons,
                                       Lats,
                                       array,
                                       cmap=colormap,
                                       norm=norm,
                                       transform=projection,
                                       zorder=1)
        else:
            plotHandle = ax.contourf(Lons,
                                     Lats,
                                     array,
                                     cmap=colormap,
                                     norm=norm,
                                     levels=levels,
                                     extend='both',
                                     transform=projection,
                                     zorder=1)

        _add_land_lakes_coastline(ax)

        if contours is not None:
            matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
            ax.contour(Lons,
                       Lats,
                       array,
                       levels=contours,
                       colors=lineColor,
                       linewidths=lineWidth,
                       transform=projection)

        cax = inset_axes(ax,
                         width='5%',
                         height='60%',
                         loc='center right',
                         bbox_to_anchor=(0.08, 0., 1, 1),
                         bbox_transform=ax.transAxes,
                         borderpad=0)

        cbar = plt.colorbar(plotHandle, cax=cax, ticks=ticks, boundaries=ticks)
        cbar.set_label(cbarlabel)
    def do_subplot(ax, field, title, colormap, norm, levels, ticks, contours,
                   lineWidth, lineColor):
        """
        Make a subplot within the figure.
        """

        data_crs = cartopy.crs.PlateCarree()
        ax.set_extent(extent, crs=data_crs)

        title = limit_title(title, maxTitleLength)
        ax.set_title(title, y=1.06, **plottitle_font)

        gl = ax.gridlines(crs=data_crs,
                          color='k',
                          linestyle=':',
                          zorder=5,
                          draw_labels=True)
        gl.xlocator = mticker.FixedLocator(np.arange(-180., 181., 20.))
        gl.ylocator = mticker.FixedLocator(np.arange(-80., 81., 10.))
        gl.n_steps = 100
        gl.right_labels = False
        gl.xformatter = cartopy.mpl.gridliner.LONGITUDE_FORMATTER
        gl.yformatter = cartopy.mpl.gridliner.LATITUDE_FORMATTER

        fieldPeriodic, lonPeriodic = add_cyclic_point(field, lon)

        LonsPeriodic, LatsPeriodic = np.meshgrid(lonPeriodic, lat)

        if levels is None:
            plotHandle = ax.pcolormesh(LonsPeriodic,
                                       LatsPeriodic,
                                       fieldPeriodic,
                                       cmap=colormap,
                                       norm=norm,
                                       transform=data_crs,
                                       zorder=1)
        else:
            plotHandle = ax.contourf(LonsPeriodic,
                                     LatsPeriodic,
                                     fieldPeriodic,
                                     cmap=colormap,
                                     norm=norm,
                                     levels=levels,
                                     transform=data_crs,
                                     zorder=1)

        _add_land_lakes_coastline(ax)

        if contours is not None:
            matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
            ax.contour(LonsPeriodic,
                       LatsPeriodic,
                       fieldPeriodic,
                       levels=contours,
                       colors=lineColor,
                       linewidths=lineWidth,
                       transform=data_crs)

        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right",
                                  size="5%",
                                  pad=0.1,
                                  axes_class=plt.Axes)
        cbar = plt.colorbar(plotHandle, cax=cax)
        cbar.set_label(cbarlabel)
        if ticks is not None:
            cbar.set_ticks(ticks)
            cbar.set_ticklabels(['{}'.format(tick) for tick in ticks])