{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_h_lat_6.py\nThis script illustrates the following concepts:\n   - Drawing filled contours of zonal wind \n   - Changing the background color for contour labels\n   - Drawing pressure and height scales\n   - Using a Blue-White-Red colormap\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/h_lat_6.ncl\n    - Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/h_lat_6_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\nfrom matplotlib.ticker import ScalarFormatter\n\nimport geocat.datafiles as gdf\nfrom geocat.viz import util as gvutil\nfrom geocat.viz import cmaps as gvcmap"
      ]
    },
    {
      "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/mxclim.nc\"))\n# Extract variables\nU = ds.U[0, :, :]"
      ]
    },
    {
      "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) and axes\nplt.figure(figsize=(8, 8))\nax = plt.axes()\n\n# Set y-axis to have log-scale\nplt.yscale('log')\n\n# Specify which contours should be drawn\nlevels = np.linspace(-55, 55, 23)\n\n# Plot contour lines\nlines = U.plot.contour(ax=ax,\n                       levels=levels,\n                       colors='black',\n                       linewidths=0.5,\n                       linestyles='solid',\n                       add_labels=False)\n\n# Draw contour labels and set their backgrounds to be white\nax.clabel(lines, fmt='%d', levels=levels)\n[\n    txt.set_bbox(dict(facecolor='white', edgecolor='none', pad=1))\n    for txt in lines.labelTexts\n]\n\n# Plot filled contours\ncolors = U.plot.contourf(ax=ax,\n                         levels=levels,\n                         cmap=gvcmap.BlWhRe,\n                         add_labels=False,\n                         add_colorbar=False)\n# Add colorbar\nplt.colorbar(colors,\n             ax=ax,\n             orientation='horizontal',\n             ticks=levels[1::2],\n             drawedges=True,\n             aspect=12,\n             shrink=0.7,\n             pad=0.1)\n\n# Use geocat.viz.util convenience function to set axes tick values\n# Set y-lim inorder for y-axis to have descending values\ngvutil.set_axes_limits_and_ticks(ax,\n                                 xticks=np.linspace(-60, 60, 5),\n                                 xticklabels=['60S', '30S', '0', '30N', '60N'],\n                                 ylim=ax.get_ylim()[::-1],\n                                 yticks=U[\"lev\"])\n\n# Change formatter or else tick values will be in exponential form\nax.yaxis.set_major_formatter(ScalarFormatter())\n\n# Use geocat.viz.util convenience function to add major tick lines with no\n# minor ticks on lefthand side y axis and some minor ticks on the x axis\ngvutil.add_major_minor_ticks(ax=ax,\n                             x_minor_per_major=3,\n                             y_minor_per_major=1,\n                             labelsize=12)\n\n# Use geocat.viz.util convenience function to add titles and the pressure label\ngvutil.set_titles_and_labels(ax,\n                             lefttitle=U.long_name,\n                             lefttitlefontsize=14,\n                             righttitle=U.units,\n                             righttitlefontsize=14,\n                             ylabel=U.lev.long_name + \" (\" + U.lev.units + \")\",\n                             labelfontsize=16)\n\n# Create second y-axis to show geo-potential height.\n# Currently we're using arbitrary values for height as we haven't figured out\n# how to make this work properly yet\naxRHS = ax.twinx()\n\n# Use geocat.viz.util convenience function to set axes tick values\ngvutil.set_axes_limits_and_ticks(axRHS,\n                                 ylim=(0, 32),\n                                 yticks=np.arange(4, 32, 4))\naxRHS.tick_params(labelsize=12)  # manually set tick label size\n\n# Use geocat.viz.util convenience function to add titles and the pressure label\ngvutil.set_titles_and_labels(axRHS, ylabel='Height (km)', labelfontsize=16)\n\n# Force the plot to be square by setting the aspect ratio to 1\nax.set_box_aspect(1)\naxRHS.set_box_aspect(1)\n\nplt.tight_layout()\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
}