{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_panel_15.py\nThis script illustrates the following concepts:\n   - Paneling three plots vertically\n   - Making a color bar span over two axes\n   - Selecting a different colormap to abide by best practices. See the `color examples <https://geocat-examples.readthedocs.io/en/latest/gallery/index.html#colors>`_ for more information.\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: http://www.ncl.ucar.edu/Applications/Scripts/panel_15.ncl\n    - Original NCL plot: http://www.ncl.ucar.edu/Applications/Images/panel_15_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\nfrom cartopy.mpl.gridliner import LongitudeFormatter, LatitudeFormatter\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport numpy as np\nimport xarray as xr\n\nimport geocat.datafiles as gdf\nimport geocat.viz.util as gvutil"
      ]
    },
    {
      "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\n# xarrays\nds = xr.open_dataset(gdf.get(\"netcdf_files/h_avg_Y0191_D000.00.nc\"), decode_times=False)\n\n# Ensure longitudes range from 0 to 360 degrees\nt = gvutil.xr_add_cyclic_longitudes(ds.T, \"lon_t\")\n\n# Selecting the first time step and then the three levels of interest\nt = t.isel(time=0)\nt_1 = t.isel(z_t=0)\nt_2 = t.isel(z_t=1)\nt_6 = t.isel(z_t=5)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = plt.figure(figsize=(8, 12))\n\ngrid = gridspec.GridSpec(nrows=3,\n                         ncols=1,\n                         figure=fig)\n\n# Choose the map projection\nproj = ccrs.PlateCarree()\n\n# Add the subplots\nax1 = fig.add_subplot(grid[0], projection=proj) # upper cell of grid\nax2 = fig.add_subplot(grid[1], projection=proj) # middle cell of grid\nax3 = fig.add_subplot(grid[2], projection=proj) # lower cell of grid\n\nfor (ax, title) in [(ax1, 'level 0'), (ax2, 'level 1'), (ax3, 'level 6')]:\n    # Use geocat.viz.util convenience function to set axes tick values\n    gvutil.set_axes_limits_and_ticks(ax=ax,\n                                     xlim=(-180, 180),\n                                     ylim=(-90, 90),\n                                     xticks=np.linspace(-180, 180, 13),\n                                     yticks=np.linspace(-90, 90, 7))\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    \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 ticks\n    gvutil.add_major_minor_ticks(ax)\n\n    # Draw coastlines\n    ax.coastlines(linewidth=0.5)\n\n    # Use geocat.viz.util convenience function to set titles\n    gvutil.set_titles_and_labels(ax,\n                                 lefttitle=t_1.long_name,\n                                 righttitle=t_1.units,\n                                 lefttitlefontsize=10,\n                                 righttitlefontsize=10)\n    # Add center title\n    ax.set_title(title, loc='center', y=1.04, fontsize=10)\n\n# Select an appropriate colormap\ncmap = 'magma'\n\n# Plot data\nC = ax1.contourf(t_1['lon_t'],\n                 t_1['lat_t'],\n                 t_1.data,\n                 levels=np.arange(0, 30, 2),\n                 cmap=cmap,\n                 extend='both')\nax2.contourf(t_2['lon_t'], \n             t_2['lat_t'],\n             t_2.data,\n             levels=np.arange(0, 30, 2),\n             cmap=cmap,\n             extend='both')\nC_2 = ax3.contourf(t_6['lon_t'],\n                   t_6['lat_t'],\n                   t_6.data,\n                   levels=np.arange(0, 22, 2),\n                   cmap=cmap,\n                   extend='both')\n\n# Add colorbars\n# By specifying two axes for `ax` the colorbar will span both of them\nplt.colorbar(C,\n             ax=[ax1, ax2],\n             ticks=range(0, 30, 2),\n             extendrect=True,\n             extendfrac='auto',\n             shrink=0.85,\n             aspect=13,\n             drawedges=True)\nplt.colorbar(C_2,\n             ax=ax3,\n             ticks=range(0, 22, 2),\n             extendrect=True,\n             extendfrac='auto',\n             shrink=0.85,\n             aspect=5.5,\n             drawedges=True)\n\nplt.show()"
      ]
    }
  ],
  "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
}