{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_conLev_1.py\nThis script illustrates the following concepts:\n   - Specifying which contour levels will be drawn\n   - Explicitly setting which contour levels will be labeled\n   - Drawing contour lines over a cylindrical equidistant map\n   - Zooming in on a particular area on a cylindrical equidistant map\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/conLev_1.ncl\n    - Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/conLev_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 cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom cartopy.mpl.gridliner import LongitudeFormatter, LatitudeFormatter\nimport matplotlib.pyplot as plt\n\nimport geocat.datafiles as gdf\nfrom geocat.viz import 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 xarrays\nds = xr.open_dataset(gdf.get(\"netcdf_files/b003_TS_200-299.nc\"),\n                     decode_times=False)\n# Extract slice of the data\ntemp = ds.TS.isel(time=43).drop_vars(names=['time'])\n# Convert from Celsius to Kelvin\ntemp.data = temp.data - 273.15\n\n# Fix the artifact of not-shown-data around 0 and 360-degree longitudes\ntemp = gvutil.xr_add_cyclic_longitudes(temp, \"lon\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Generate figure (set its size (width, height) in inches)\nplt.figure(figsize=(12, 6))\n\n# Generate axes using Cartopy projection\nprojection = ccrs.PlateCarree()\nax = plt.axes(projection=projection)\nax.set_extent([-180, 180, -70, 70], crs=projection)\n\n# Draw land\nax.add_feature(cfeature.LAND, color='silver')\n\n# Use geocat.viz.util convenience function to set axes tick values\ngvutil.set_axes_limits_and_ticks(ax,\n                                 xticks=np.linspace(-180, 180, 13),\n                                 yticks=np.linspace(-60, 60, 5))\n\n# Use geocat.viz.util convenience function to make latitude, longitude tick labels\ngvutil.add_lat_lon_ticklabels(ax)\n# Removing degree symbol from tick labels to more closely resemble NCL example\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, labelsize=12)\n\n# Use geocat.viz.util convenience function to add titles\ngvutil.set_titles_and_labels(ax,\n                             lefttitle=temp.long_name,\n                             righttitle=temp.units,\n                             lefttitlefontsize=14,\n                             righttitlefontsize=14)\n\n# Add lower text box\nax.text(1,\n        -0.15,\n        \"CONTOUR FROM -5 TO 30 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# Specify which contour levels to draw\ncontour_lev = np.arange(-5, 35, 5)\n# Specify which contour lines to label. Where the labels appear on the contours\n# is handeled by xarray.plot.contour(). The keyword manual can be used to\n# set exactly where the labels will be drawn.\nlabels = np.linspace(0, 20, 3)\n# Plot contour lines\ncontour = temp.plot.contour(ax=ax,\n                            transform=ccrs.PlateCarree(),\n                            vmin=-5,\n                            vmax=30,\n                            levels=contour_lev,\n                            colors='black',\n                            linestyles='solid',\n                            linewidths=0.5,\n                            add_labels=False)\nax.clabel(contour, labels, fmt='%d', inline=True, fontsize=10)\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
}