{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_conLab_4.py\nThis script illustrates the following concepts:\n   - Drawing color-filled contours over a cylindrical equidistant map\n   - Setting the background fill color for contour labels to white\n   - Manually select where contour labels will be drawn\n   - Changing the contour level spacing\n   - Zooming in on a particular area on a cylindrical equidistant map\n   - Creating left and right titles\n   - Creating a horizontal colorbar\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/conLab_4.ncl\n    - Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/conLab_4_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 cmaps as gvcmaps\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/uv300.nc\"), decode_times=False)\nU = ds.isel(time=1, drop=True).U\n\n# Reduce the dataset to something just bigger than the area we want to plot.\n# This will improve how the contour lines are labeled\nU = U.where(U.lon >= 0)\nU = U.where(U.lon <= 71)\nU = U.where(U.lat >= -33)\nU = U.where(U.lat <= 33)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.figure(figsize=(8, 8))\n\n# Create axes using the Plate Carree rectangular projection\nax = plt.axes(projection=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# Zoom in on region bounded by the prime meridian, 70N, 25S, and 25N\nax.set_extent([0, 70, -30, 30], crs=ccrs.PlateCarree())\n\n# Use geocat.viz.util convenience function to set axes tick values\ngvutil.set_axes_limits_and_ticks(ax,\n                                 yticks=np.linspace(-20, 20, 3),\n                                 xticks=np.linspace(0, 60, 3))\n\n# Use geocat.viz.util convenience function to make plots look like NCL plots\n# by 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=4,\n                             labelsize=14)\n\n# Use geocat.viz.util convenience function to add titles to left and right of\n# the plot axis\ngvutil.set_titles_and_labels(ax, lefttitle=U.long_name, righttitle=U.units)\n\n# Select a color map\ncmap = gvcmaps.gui_default\n\n# Draw filled contours\ncolors = U.plot.contourf(ax=ax,\n                         cmap=cmap,\n                         levels=np.arange(-16, 48, 4),\n                         add_colorbar=False,\n                         add_labels=False)\n# Draw contour lines\nlines = U.plot.contour(ax=ax,\n                       colors='black',\n                       levels=np.arange(-16, 48, 4),\n                       linewidths=0.5,\n                       linestyles='solid',\n                       add_labels=False)\n\n# Create horizontal colorbar\ncbar = plt.colorbar(colors,\n                    ticks=np.arange(-12, 44, 4),\n                    orientation='horizontal',\n                    drawedges=True,\n                    aspect=12,\n                    shrink=0.8,\n                    pad=0.075)\ncbar.ax.tick_params(labelsize=14)  # Make the labels larger\n\n# Specify coordinates for contour labels in (longitude, latitude) format\nmanual = [(25, 28), (30, -17),\n          (40, -21), (40, -5),\n          (42, -13), (10, 50),\n          (62, -15), (65, -2)]\n\n# Draw contour labels and pass in coordinates using `manual` argument\nax.clabel(lines, fontsize=12, fmt='%d', inline=True, manual=manual)\n\n# Set label backgrounds white\n[\n    txt.set_bbox(dict(facecolor='white', edgecolor='none', pad=2))\n    for txt in lines.labelTexts\n]\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
}