{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_overlay_1.py\nThis script illustrates the following concepts:\n   - Overlaying line contours on filled contours\n   - Explicitly setting contour levels\n   - Adding custom formatted contour labels\n   - Manually selecting where contour labels will be drawn\n   - Adding label textbox\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/overlay_1.ncl\n    - Original NCL plots: https://www.ncl.ucar.edu/Applications/Images/overlay_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 numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom cartopy.mpl.gridliner import LongitudeFormatter, LatitudeFormatter\n\nimport geocat.datafiles as gdf\nfrom geocat.viz import util as gvutil\nfrom geocat.viz import cmaps as gvcmaps"
      ]
    },
    {
      "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/80.nc\"))\n\n# Extract slice of data\nu = ds.U.isel(time=0).drop('time').isel(lev=10).drop('lev')\nt = ds.T.isel(time=0).drop('time').isel(lev=10).drop('lev')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Specify levels and color map for contour\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "t_lev = np.arange(210, 275, 5)\ncmap = gvcmaps.BlueDarkRed18\nu_lev = np.arange(-5, 40, 5)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Crate plot:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.figure(figsize=(10, 8))\nax = plt.axes(projection=ccrs.PlateCarree())\n\n# Set extent around US\nax.set_extent([230, 300, 20, 60], crs=ccrs.PlateCarree())\n\n# Draw map features\nax.add_feature(cfeature.LAKES,\n               linewidth=0.5,\n               edgecolor='black',\n               facecolor='None')\nax.add_feature(cfeature.COASTLINE, linewidth=0.5)\n\n# Plot filled contour\ntemp = t.plot.contourf(ax=ax,\n                       transform=ccrs.PlateCarree(),\n                       cmap=cmap,\n                       levels=t_lev,\n                       extend='neither',\n                       add_colorbar=False,\n                       add_labels=False)\nplt.colorbar(temp,\n             ax=ax,\n             ticks=np.arange(215, 270, 5),\n             orientation='horizontal',\n             pad=0.075)\n\n# Plot line contour\nwind = u.plot.contour(ax=ax,\n                      transform=ccrs.PlateCarree(),\n                      vmin=-5,\n                      vmax=35,\n                      levels=u_lev,\n                      colors='black',\n                      linewidths=0.5,\n                      add_labels=False)\n\n# Manually specify where contour labels will go using lat and lon coordiantes\nmanual = [(-107, 52), (-79, 57), (-78, 47), (-103, 32), (-86, 23)]\nax.clabel(wind, u_lev, fmt='%d', inline=True, fontsize=10, manual=manual)\n\n# Set label backgrounds white\n[\n    txt.set_bbox(dict(facecolor='white', edgecolor='none', pad=2))\n    for txt in wind.labelTexts\n]\n\n# Add lower text box\nax.text(1,\n        -0.3,\n        \"CONTOUR FROM -5 TO 35 BY 5\",\n        horizontalalignment='right',\n        transform=ax.transAxes,\n        bbox=dict(boxstyle='square, pad=0.25',\n                  facecolor='white',\n                  edgecolor='black'))\n\n# Use geocat.viz.util convenience function to set titles and labels\ngvutil.set_titles_and_labels(ax,\n                             maintitle=r\"$\\bf{T/U @500hPa}$\",\n                             lefttitle=t.long_name,\n                             righttitle=t.units)\n# Add secondary title below the one placed by gvutil\nax.text(0, 1.01, u.long_name, transform=ax.transAxes)\nax.text(0.97, 1.01, u.units, transform=ax.transAxes)\n\n# Use geocat.viz.util convenience function to make plots look like NCL plots by\n# using latitude, longitude tick labels\ngvutil.add_lat_lon_ticklabels(ax)\n\n# Remove the degree symbol from tick labels\nax.yaxis.set_major_formatter(LatitudeFormatter(degree_symbol=''))\nax.xaxis.set_major_formatter(LongitudeFormatter(degree_symbol=''))\n\n# Use geocat.viz.util convenience function to add minor and major tick lines\ngvutil.add_major_minor_ticks(ax,\n                             x_minor_per_major=3,\n                             y_minor_per_major=5,\n                             labelsize=12)\n\n# Use geocat.viz.util convenience function to set axes tick values\ngvutil.set_axes_limits_and_ticks(ax,\n                                 xticks=np.arange(-120, -30, 30),\n                                 yticks=np.arange(20, 70, 10))\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
}