{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_vector_1.py\nPlot U & V vector over SST\n\nThis script illustrates the following concepts:\n  - Overlaying vectors and filled contours on a map\n  - Changing the scale of the vectors on the plot\n  - Moving the vector reference annotation to the top right of the plot\n  - Setting the color for vectors\n  - Increasing the thickness of vectors\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/vector_1.ncl\n    - Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/vector_1_lg.png\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Import necessary packages\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import xarray as xr\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport cartopy\nimport cartopy.crs as ccrs\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\nsst_in = xr.open_dataset(gdf.get(\"netcdf_files/sst8292.nc\"))\nuv_in = xr.open_dataset(gdf.get(\"netcdf_files/uvt.nc\"))\n\n# Use date as the dimension rather than time\nsst_in = sst_in.set_coords(\"date\").swap_dims({\"time\": \"date\"}).drop('time')\nuv_in = uv_in.set_coords(\"date\").swap_dims({\"time\": \"date\"}).drop('time')\n\n# Extract required variables\n# Read SST and U, V for Jan 1988 (at 1000 mb for U, V)\n# Note that we could use .isel() if we know the indices of date and lev\nsst = sst_in['SST'].sel(date=198801)\nu = uv_in['U'].sel(date=198801, lev=1000)\nv = uv_in['V'].sel(date=198801, lev=1000)\n\n# Read in grid information\nlat_sst = sst['lat']\nlon_sst = sst['lon']\nlat_uv = u['lat']\nlon_uv = u['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.subplots(figsize=(10, 7))\n\n# Generate axes using Cartopy projection\nax = plt.axes(projection=ccrs.PlateCarree())\n\n# Draw vector plot\nQ = plt.quiver(lon_uv,\n               lat_uv,\n               u,\n               v,\n               color='white',\n               pivot='middle',\n               width=.0025,\n               scale=75,\n               zorder=2)\n\n# Turn on continent shading\nax.add_feature(cartopy.feature.LAND,\n               edgecolor='lightgray',\n               facecolor='lightgray',\n               zorder=1)\n\n# Define levels for contour map (24, 24.1, ..., 28.8, 28.9)\nlevels = np.linspace(24, 28.9, 50)\n\n# Import an NCL colormap, truncating it by using geocat.viz.util convenience function\ngvutil.truncate_colormap(gvcmaps.BlAqGrYeOrReVi200,\n                         minval=0.08,\n                         maxval=0.96,\n                         n=len(levels),\n                         name='BlAqGrYeOrReVi200')\n\n# Contourf-plot the SST data\ncf = sst.plot.contourf('lon',\n                       'lat',\n                       extend='both',\n                       levels=levels,\n                       cmap='BlAqGrYeOrReVi200',\n                       zorder=0,\n                       add_labels=False,\n                       add_colorbar=False)\n\n# Add color bar\ncbar_ticks = np.arange(24, 29.1, .3)\ncbar = plt.colorbar(cf, \n                    orientation='vertical', \n                    drawedges=True, \n                    shrink=0.75, \n                    pad=0.05,\n                    ticks=cbar_ticks)\n\n# Draw the key for the quiver plot as a rectangle patch\nrect = plt.Rectangle((92.9, 22.6),\n                     2,\n                     2,\n                     facecolor='white',\n                     edgecolor=None,\n                     zorder=2)\nax.add_patch(rect)\nax.quiverkey(Q,\n             0.9675,\n             0.9,\n             3,\n             '4',\n             labelpos='N',\n             color='black',\n             coordinates='axes',\n             fontproperties={'size': 14},\n             labelsep=0.1)\n\n# Use geocat.viz.util convenience function to set axes tick values\ngvutil.set_axes_limits_and_ticks(ax,\n                                 xlim=(65, 95),\n                                 ylim=(5, 25),\n                                 xticks=range(70, 95, 10),\n                                 yticks=range(5, 27, 5))\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=5,\n                             y_minor_per_major=5,\n                             labelsize=14)\n\n# Use geocat.viz.util convenience function to make plots look like NCL plots by using latitude, longitude tick labels\ngvutil.add_lat_lon_ticklabels(ax)\n\n# Use geocat.viz.util convenience function to add titles to left and right of the plot axis.\ngvutil.set_titles_and_labels(ax,\n                             lefttitle='Sea Surface Temperature',\n                             righttitle='C')\n\n# Show the plot\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
}