{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_panel_19.py\nThis script illustrates the following concepts:\n   - Paneling four subplots in a two by two grid using ``gridspec``\n   - Adjusting the positioning of the subplots using ``hspace`` and ``wspace``\n   - Using a blue-red color map\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/dev_1.ncl\n    - Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/dev_1_lg.png\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Import packages:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom cartopy.mpl.gridliner import LongitudeFormatter, LatitudeFormatter\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport xarray as xr\n\nimport geocat.datafiles as gdf\nfrom geocat.viz import cmaps as gvcmaps\nimport geocat.viz.util as gvutil"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Helper function to convert date from YYYYMM to the month name and the year\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def convert_date(date):\n    months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',\n              'August', 'September', 'October', 'November', 'December']\n    year = str(date)[:4]\n    month = months[int(str(date)[4:]) - 1]\n    return month + \" \" + year"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Helper function to create and format subplots\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def add_axes(fig, grid_space, date):\n    ax = fig.add_subplot(grid_space, projection=ccrs.PlateCarree(central_longitude=-160))\n    ax.set_extent([100, 300, -60, 60], crs=ccrs.PlateCarree())\n\n    # Usa geocat.viz.util convenience function to set axes parameters\n    gvutil.set_axes_limits_and_ticks(ax,\n                                     ylim=(-60, 60),\n                                     xticks=np.arange(-80, 120, 30),\n                                     yticks=np.arange(-60, 61, 30))\n\n    # Use geocat.viz.util convenience function to make plots look like NCL\n    # plots by using latitude, longitude tick labels\n    gvutil.add_lat_lon_ticklabels(ax)\n    # Remove the degree symbol from tick labels\n    ax.yaxis.set_major_formatter(LatitudeFormatter(degree_symbol=''))\n    ax.xaxis.set_major_formatter(LongitudeFormatter(degree_symbol=''))\n\n    # Use geocat.viz.util convenience function to add minor and major tick lines\n    gvutil.add_major_minor_ticks(ax, labelsize=8)\n\n    # Make sure that tick marks are only on the left and bottom sides of subplot\n    ax.tick_params('both', which='both', top=False, right=False)\n    \n    # Add land to the subplot\n    ax.add_feature(cfeature.LAND,\n                   facecolor='lightgray',\n                   edgecolor='black',\n                   linewidths=0.5,\n                   zorder=2)\n\n    # Set subplot titles\n    gvutil.set_titles_and_labels(ax,\n                                 lefttitle='degC',\n                                 lefttitlefontsize=10,\n                                 righttitle='$(W m s^{-2})$',\n                                 righttitlefontsize=10)\n    ax.set_title(convert_date(date), fontsize=10, y=1.04)\n\n    return ax"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Helper function to create figure with specific gridspec\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def create_fig(grid, fig, title):\n    # Add the axes\n    ax1 = add_axes(fig, grid[0, 0], dates[0])\n    ax2 = add_axes(fig, grid[0, 1], dates[1])\n    ax3 = add_axes(fig, grid[1, 0], dates[2])\n    ax4 = add_axes(fig, grid[1, 1], dates[3])\n\n    # Create a dictionary with contour attributes\n    contourf_kw = dict(transform=ccrs.PlateCarree(),\n                      levels=21,\n                      cmap=gvcmaps.BlueRed,\n                      add_colorbar=False,\n                      add_labels=False,\n                      vmin=-5,\n                      vmax=5,\n                      extend='both',\n                      zorder=1)\n\n    # Plot the filled contours\n    contour1 = data1.plot.contourf(ax=ax1, **contourf_kw)\n    contour2 = data2.plot.contourf(ax=ax2, **contourf_kw)\n    contour3 = data3.plot.contourf(ax=ax3, **contourf_kw)\n    contour4 = data4.plot.contourf(ax=ax4, **contourf_kw)\n\n    # Add colorbar for all four plots\n    fig.colorbar(contour4, ax=[ax1, ax2, ax3, ax4], ticks=np.linspace(-5, 5, 11),\n                 drawedges=True, orientation='horizontal', shrink=0.5, pad=0.075,\n                 extendfrac='auto', extendrect=True)\n\n    # Add figure title\n    fig.suptitle(title, fontsize=18, y=0.9)\n\n    plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Read in data:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Open a netCDF data file using xarray default engine and load the data into xarrays\nds = xr.open_dataset(gdf.get(\"netcdf_files/sst8292a.nc\"))\n\ndates = [198212, 199008, 198705, 198411]\n\ndata1 = ds.sel(time=11).SSTA\ndata1 = gvutil.xr_add_cyclic_longitudes(data1, 'lon')\n\ndata2 = ds.sel(time=103).SSTA\ndata2 = gvutil.xr_add_cyclic_longitudes(data2, 'lon')\n\ndata3 = ds.sel(time=64).SSTA\ndata3 = gvutil.xr_add_cyclic_longitudes(data3, 'lon')\n\ndata4 = ds.sel(time=34).SSTA\ndata4 = gvutil.xr_add_cyclic_longitudes(data4, 'lon')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot with default spacing:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = plt.figure(figsize=(10, 10))\n\n# Create gridspec to hold four subplots\ngrid = fig.add_gridspec(ncols=2, nrows=2)\n\ntitle = \"Default spacing between plots\"\n\n# Create the figure with the given title and gridspec\ncreate_fig(grid, fig, title)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot with reduced spacing between the left and right subplots \n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = plt.figure(figsize=(10, 10))\n\n# Create gridspec to hold four subplots, use `wspace` to specify the amount\n# of spacing between columns of subplots\ngrid = fig.add_gridspec(ncols=2, nrows=2, wspace=0.125)\n\ntitle = \"Reduced spacing between left and right plots\"\n\ncreate_fig(grid, fig, title)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot with reduced spacing between the top and bottom subplots \n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = plt.figure(figsize=(10, 10))\n\n# Create gridspec to hold four subplots, use `hspace` to specify the amount\n# of spacing between rows of subplots\ngrid = fig.add_gridspec(ncols=2, nrows=2, wspace=0.125, hspace=-0.15)\n\ntitle = \"Reduced spacing between top and bottom plots\"\n\ncreate_fig(grid, fig, title)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.9"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}