{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_lb_4.py\nThis script illustrates the following concepts:\n   - Drawing a horizontal colorbar\n   - Changing the labelbar labels\n   - Adding a title to a labelbar\n   - Changing the font of the labelbar's labels\n   - Making the labelbar label fonts smaller\n   - Centering the labels inside each box in a labelbar\n   - Adding a vertical title to a labelbar\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/lb_4.ncl\n    - Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/lb_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\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/atmos.nc\"), decode_times=False)\n\n# Extract slice of data\nV = ds.V.isel(time=0, lev=3)\n\n# Fix the artifact of not-shown-data around 0 and 360-degree longitudes\nV = gvutil.xr_add_cyclic_longitudes(V, \"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)\nfig = plt.figure(figsize=(10, 6))\n\n# Generate axes using Cartopy and draw coastlines\nax = plt.axes(projection=ccrs.PlateCarree())\nax.coastlines(linewidths=0.5, alpha=0.6)\n\n# Use geocat.viz.util convenience function to set axes limits & tick values\ngvutil.set_axes_limits_and_ticks(ax,\n                                 xlim=(-180, 180),\n                                 ylim=(-90, 90),\n                                 xticks=np.linspace(-180, 180, 13),\n                                 yticks=np.linspace(-90, 90, 7))\n\n# Use geocat.viz.util convenience function to add minor and major tick lines\ngvutil.add_major_minor_ticks(ax, labelsize=10)\n\n# Use geocat.viz.util convenience function to make latitude, longitude tick labels\ngvutil.add_lat_lon_ticklabels(ax)\n# Remove 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 titles\ngvutil.set_titles_and_labels(ax,\n                             lefttitle=V.long_name,\n                             righttitle=V.units,\n                             lefttitlefontsize=12,\n                             righttitlefontsize=12)\n\n# Import an NCL colormap\ncmap = gvcmaps.wgne15\n\n# Specify which contour levels to draw\ncontour_lev = np.arange(-20, 28, 4)\n# Plot filled contour\ncontour = V.plot.contourf(ax=ax,\n                          transform=ccrs.PlateCarree(),\n                          cmap=cmap,\n                          levels=contour_lev,\n                          add_colorbar=False,\n                          add_labels=False)\n# Plot line contour\nV.plot.contour(ax=ax,\n               transform=ccrs.PlateCarree(),\n               colors='black',\n               linewidths=0.5,\n               linestyles='solid',\n               levels=contour_lev,\n               add_colorbar=False,\n               add_labels=False)\n\n# Create horizontal colorbar\n# By changing the kwarg `pad`, the colorbar can be moved closer to or farther\n# away from the axis parallel to it. `pad` defaults to 0.15 for horizontal\n# colorbars. `extendrect` and `extendfrac` format the ends of the colorbar,\n# default is pointed ends to show there are values beyond the given contour\n# levels\ncbar = plt.colorbar(contour,\n                    ax=ax,\n                    orientation='horizontal',\n                    shrink=0.5,\n                    pad=0.11,\n                    extendrect=True,\n                    extendfrac='auto',\n                    aspect=11,\n                    drawedges=True)\n\n# Turn off automatically created ticks and tick labels\ncbar.ax.set_xticklabels([])\ncbar.ax.get_xaxis().set_ticks([])\n\n# Draw text in the center of each box\noffset = 1 / 13 / 2\nfor i in range(1, 14):\n    cbar.ax.text(i / 13 - offset,\n                 0.45,\n                 i,\n                 horizontalalignment='center',\n                 verticalalignment='center',\n                 fontweight='bold',\n                 transform=cbar.ax.transAxes)\n\n# Draw the colorbar title\ncbar.ax.text(1.1,\n             0.5,\n             V.units,\n             horizontalalignment='center',\n             verticalalignment='center',\n             transform=cbar.ax.transAxes)\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
}