{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# NCL_polyg_8.py\nThis script illustrates the following concepts:\n   - Drawing a scatter plot on a map\n   - Changing the marker color and size in a map plot\n   - Plotting station locations using markers\n   - Manually creating a legend using markers and text\n   - Adding text to a plot\n   - Generating dummy data using \"random_uniform\"\n   - Binning data\n\nSee following URLs to see the reproduced NCL plot & script:\n    - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/polyg_8.ncl\n    - Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/polyg_8_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 cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nfrom cartopy.mpl.gridliner import LongitudeFormatter, LatitudeFormatter\nimport matplotlib.pyplot as plt\n\nfrom geocat.viz import util as gvutil"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Generate dummy data\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "npts = 100\nrandom = np.random.default_rng(seed=1)\n# Create random coordinates to position the markers\nlat = random.uniform(low=25, high=50, size=npts)\nlon = random.uniform(low=-125, high=-70, size=npts)\n# Create random data which the color will be based off of\nr = random.uniform(low=-1.2, high=35, size=npts)\n\nbins = [0, 5, 10, 15, 20, 23, 26]\ncolors = [\n    'mediumpurple', 'mediumblue', 'blue', 'green', 'limegreen', 'greenyellow',\n    'gold', 'orangered'\n]\n# increasing sizes for the markers in each bin\nsizes = np.linspace(15, 25, len(bins))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.figure(figsize=(9, 6))\nprojection = ccrs.PlateCarree()\nax = plt.axes(projection=projection)\nax.set_extent([-125, -70, 25, 50], crs=projection)\n\n# Draw land\nax.add_feature(cfeature.LAND, color='silver', zorder=0)\nax.add_feature(cfeature.LAKES, color='white', zorder=0)\n\n# Use geocat.viz.util convenience function to set axes tick values\ngvutil.set_axes_limits_and_ticks(ax,\n                                 xticks=np.linspace(-120, -80, 3),\n                                 yticks=np.linspace(30, 50, 3))\n\n# Use geocat.viz.util convenience function to make latitude and longitude tick\n# labels\ngvutil.add_lat_lon_ticklabels(ax)\n# Removing degree symbol from tick labels to more closely resemble NCL example\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 minor and major tick lines\ngvutil.add_major_minor_ticks(ax,\n                             x_minor_per_major=4,\n                             y_minor_per_major=5,\n                             labelsize=12)\n\n# Use geocat.viz.util convenience function to add titles\ngvutil.set_titles_and_labels(\n    ax,\n    maintitlefontsize=16,\n    maintitle=\n    \"Dummy station data colored and\\nsized according to range of values\")\n\n# Plot markers with values less than first bin value\nmasked_lon = np.where(r < bins[0], lon, np.nan)\nmasked_lat = np.where(r < bins[0], lat, np.nan)\nlabel = \"x < \" + str(bins[0])\nplt.scatter(masked_lon,\n            masked_lat,\n            label=label,\n            s=sizes[0],\n            color=colors[0],\n            zorder=1)\n\n# Plot all other markers but those in the last bin\nlabel_format = \"{} <= x < {}\"\nfor x in range(1, len(bins)):\n    masked_lon = np.where(bins[x - 1] <= r, lon, np.nan)\n    masked_lon = np.where(r < bins[x], masked_lon, np.nan)\n    masked_lat = np.where(bins[x - 1] <= r, lat, np.nan)\n    masked_lat = np.where(r < bins[x], masked_lat, np.nan)\n    label = label_format.format(bins[x - 1], bins[x])\n    plt.scatter(masked_lon,\n                masked_lat,\n                label=label,\n                s=sizes[x],\n                color=colors[x],\n                zorder=1)\n\n# Plot markers with values greater than or equal to last bin value\nmasked_lon = np.where(r >= bins[-1], lon, np.nan)\nmasked_lat = np.where(r >= bins[-1], lat, np.nan)\nlabel = \"x >= \" + str(bins[-1])\nplt.scatter(masked_lon,\n            masked_lat,\n            label=label,\n            s=sizes[-1],\n            color=colors[-1],\n            zorder=1)\n\n# `ncol` being equal to half of the number of labels makes the legend appear\n# horizontal with two rows\nlegend = ax.legend(bbox_to_anchor=(-0.05, -0.3),\n                   ncol=4,\n                   loc='lower left',\n                   columnspacing=4.75,\n                   frameon=False)\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
}