{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_xy_16.py\nThis script illustrates the following concepts:\n   - Drawing a legend inside an XY plot\n   - Drawing an X reference line in an XY plot\n   - Reversing the Y axis\n   - Using log scaling and explicit labeling\n   - Changing the labels in a legend\n   - Creating a vertical profile plot\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/xy_16.ncl\n    - Original NCL plots: https://www.ncl.ucar.edu/Applications/Images/xy_16_1_lg.png and https://www.ncl.ucar.edu/Applications/Images/xy_16_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 numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import (ScalarFormatter, NullFormatter)\nimport matplotlib.ticker as tic\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/atmos.nc\"), decode_times=False)\nU = ds.U.isel(time=0).drop('time').isel(lon=0).drop('lon')\n\n# Extract slices of the data at different latitudes using the index of the desired value\nU20 = U.isel(lat=39).drop('lat')\nU30 = U.isel(lat=42).drop('lat')\nU40 = U.isel(lat=46).drop('lat')\nU50 = U.isel(lat=49).drop('lat')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot with linear y axis:\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# 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=4,\n                             labelsize=14)\n\n# Use geocat.viz.util convenience function to set axes parameters\ngvutil.set_axes_limits_and_ticks(ax,\n                                 xlim=(-20, 40),\n                                 ylim=(1000, 0),\n                                 xticks=np.arange(-20, 60, 10),\n                                 yticks=np.arange(0, 1200, 200))\n\n# Use geocat.viz.util convenience function to set titles and labels\ngvutil.set_titles_and_labels(ax,\n                             maintitle='Profile Plot',\n                             xlabel=U.long_name,\n                             ylabel=U['lev'].long_name)\n\n# Add reference line x=0\nax.axvline(x=0, color='black', linewidth=0.5)\n\n# Plot data\nplt.plot(U20.data,\n         U20.lev,\n         color='black',\n         linestyle='solid',\n         label='20N',\n         linewidth=0.5)\nplt.plot(U30.data,\n         U30.lev,\n         color='black',\n         dashes=[15, 5],\n         label='30N',\n         linewidth=0.5)\nplt.plot(U40.data,\n         U40.lev,\n         color='black',\n         dashes=[4, 5],\n         label='40N',\n         linewidth=0.5)\nplt.plot(U50.data,\n         U50.lev,\n         color='black',\n         dashes=[15, 5, 5, 5],\n         label='50N',\n         linewidth=0.5)\n\n# Add legend\nhandles, labels = ax.get_legend_handles_labels()\n# Default order is the order in which the data was plotted\nhandles = reversed(handles)  # Reverse order of legend elements\nlabels = reversed(labels)\nplt.legend(handles,\n           labels,\n           loc='center right',\n           frameon=False,\n           fontsize=14,\n           labelspacing=1)\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot with logarithmic y axis:\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# Note: Currently geocat-viz does not have a utility function for formating\n# major and minor ticks on logarithmic axes.\nplt.yscale('log')\nax.yaxis.set_major_formatter(ScalarFormatter())\nax.yaxis.set_minor_formatter(NullFormatter())\nax.tick_params(labelsize=14)\nax.minorticks_on()\nax.xaxis.set_minor_locator(tic.AutoMinorLocator(n=5))\n# Specify no minor ticks on log y axis\nax.yaxis.set_minor_locator(tic.LogLocator())\n# Length and width are in points and may need to change depending on figure size\nax.tick_params(\"both\",\n               length=8,\n               width=0.9,\n               which=\"major\",\n               bottom=True,\n               top=True,\n               left=True,\n               right=True)\nax.tick_params(\"both\",\n               length=4,\n               width=0.4,\n               which=\"minor\",\n               bottom=True,\n               top=True,\n               left=True,\n               right=True)\n\n# Use geocat.viz.util convenience function to set axes parameters\npressure_lvls = [1, 5, 10, 30, 50, 100, 200, 300, 400, 500, 700, 1000]\ngvutil.set_axes_limits_and_ticks(ax,\n                                 xlim=(-20, 40),\n                                 ylim=(1000, 4),\n                                 xticks=np.arange(-20, 60, 10),\n                                 yticks=pressure_lvls)\n\n# Use geocat.viz.util convenience function to set titles and labels\ngvutil.set_titles_and_labels(ax, maintitle='Profile Plot', xlabel=U.long_name)\n\n# Plot data\nplt.plot(U20.data,\n         U20.lev,\n         color='black',\n         linestyle='solid',\n         label='20N',\n         linewidth=0.5)\nplt.plot(U30.data,\n         U30.lev,\n         color='black',\n         dashes=[15, 5],\n         label='30N',\n         linewidth=0.5)\nplt.plot(U40.data,\n         U40.lev,\n         color='black',\n         dashes=[4, 5],\n         label='40N',\n         linewidth=0.5)\nplt.plot(U50.data,\n         U50.lev,\n         color='black',\n         dashes=[15, 5, 5, 5],\n         label='50N',\n         linewidth=0.5)\n\n# Add legend\nhandles, labels = ax.get_legend_handles_labels()\n# Default order is the order in which the data was plotted\nhandles = reversed(handles)  # Reverse order of legend elements\nlabels = reversed(labels)\nplt.legend(handles,\n           labels,\n           loc='center right',\n           frameon=False,\n           fontsize=14,\n           labelspacing=1)\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
}