{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_lcmask_1.py\nThis script illustrates the following concepts:\n   - Drawing filled contours over a Lambert Conformal map\n   - Zooming in on a particular area on a Lambert Conformal map\n   - Creating a custom plot boundary\n   - Using a blue-white-red color map\n   - Setting contour levels using a min/max contour level and a spacing\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: http://ncl.ucar.edu/Applications/Scripts/lcmask_1.ncl\n    - Original NCL plot: http://ncl.ucar.edu/Applications/Images/lcmask_1_1_lg.png and http://ncl.ucar.edu/Applications/Images/lcmask_1_2_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\nimport matplotlib.path as mpath\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport xarray as xr\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\n# xarrays and disable time decoding due to missing necessary metadata\nds = xr.open_dataset(gdf.get(\"netcdf_files/atmos.nc\"), decode_times=False)\n# Extract a slice of the data\nds = ds.isel(time=0).drop_vars(names=[\"time\"])\nds = ds.isel(lev=0).drop_vars(names=[\"lev\"])\nV = ds.V\n# Ensure longitudes range from 0 to 360 degrees\nV = gvutil.xr_add_cyclic_longitudes(V, \"lon\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot unmasked data:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Generate figure and projection using Cartopy\nplt.figure(figsize=(7, 10))\nproj = ccrs.LambertConformal(central_longitude=0, standard_parallels=(45, 89))\n# Set axis projection\nax = plt.axes(projection=proj, frameon=False)\n# Set extent to include all longitudes and the northern hemisphere\nax.set_extent((0, 359, 0, 89), crs=ccrs.PlateCarree())\nax.coastlines(linewidth=0.5)\n\n# Plot data and create colorbar\nnewcmp = gvcmaps.BlWhRe\n\nwind = V.plot.contourf(ax=ax,\n                       cmap=newcmp,\n                       transform=ccrs.PlateCarree(),\n                       add_colorbar=False,\n                       levels=24)\ncbar = plt.colorbar(wind,\n                    ax=ax,\n                    orientation='horizontal',\n                    drawedges=True,\n                    ticks=np.arange(-48, 48, 8),\n                    pad=0.1,\n                    aspect=12)\ncbar.ax.tick_params(length=0)  # remove tick marks but leave in labels\n\n# Use geocat.viz.util convenience function to add left and right titles\ngvutil.set_titles_and_labels(ax,\n                             lefttitle=V.long_name,\n                             lefttitlefontsize=16,\n                             righttitle=V.units,\n                             righttitlefontsize=16)\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Mask data\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "masked = V.where(V.lat > 20)\nmasked = masked.where(masked.lat < 80)\nmasked = masked.where(masked.lon > 90)\nmasked = masked.where(masked.lon < 220)\n\n# Rotate data to match NCL example\nmasked['lon'] = masked['lon'] + 180"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot masked data\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Generate figure and projection using Cartopy\nplt.figure(figsize=(10, 7))\nproj = ccrs.LambertConformal(central_longitude=-22.5,\n                             standard_parallels=(45, 89))\n# Set axis projection\nax = plt.axes(projection=proj)\nax.coastlines(linewidth=0.5)\n\n# Make a custom boundary using convenience function\ngvutil.set_map_boundary(ax, [-85, 40], [20, 80], south_pad=1)\n\n# Plot data and create colorbar\nwind = masked.plot.contourf(ax=ax,\n                            cmap=newcmp,\n                            transform=ccrs.PlateCarree(),\n                            add_colorbar=False,\n                            levels=24)\ncbar = plt.colorbar(wind,\n                    ax=ax,\n                    orientation='horizontal',\n                    drawedges=True,\n                    ticks=np.arange(-40, 44, 4),\n                    pad=0.1,\n                    aspect=18)\ncbar.ax.tick_params(length=0)  # remove tick marks but leave in labels\n\n# Use geocat.viz.util convenience function to add left and right titles\ngvutil.set_titles_and_labels(ax,\n                             lefttitle=V.long_name,\n                             lefttitlefontsize=16,\n                             righttitle=V.units,\n                             righttitlefontsize=16)\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
}