{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/niconoe/pyinaturalist/main?filepath=examples%2FData%2520Visualizations%2520-%2520Matplotlib.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Matplotlib example\n",
    "Here is an example of making a simple seasonality chart using [matplotlib](https://matplotlib.org/).\n",
    "\n",
    "This shows observations counts by month (all years) for monarch butterflies observed in the state of Iowa."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "from pyinaturalist import get_observations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "590\n"
     ]
    }
   ],
   "source": [
    "# Then, get all observations in that place of a given species\n",
    "observations = get_observations(\n",
    "    taxon_name='Danaus plexippus',\n",
    "    photos=True,\n",
    "    geo=True,\n",
    "    geoprivacy='open',\n",
    "    place_id=24,\n",
    "    page='all',\n",
    ")\n",
    "print(len(observations))\n",
    "\n",
    "# Flatten nested JSON values\n",
    "df = pd.json_normalize(observations)\n",
    "df['observed_month'] = df['observed_on'].apply(lambda x: x.month)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "tags": [
     "nbsphinx-thumbnail"
    ]
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 13520 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Plot observation counts by month\n",
    "df['observed_month'].groupby(df['observed_month']).count().plot(kind='area')\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "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.9.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
