{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[](https://mybinder.org/v2/gh/pyinat/pyinaturalist/main?filepath=examples%2FData%2520Visualizations%2520-%2520Seaborn.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Seaborn examples\n", "Here are some examples of visualizations that can be created using [Seaborn](https://seaborn.pydata.org/)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "from datetime import datetime\n", "from dateutil import tz\n", "from os.path import exists\n", "from pprint import pprint\n", "\n", "import seaborn as sns\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib as mpl\n", "from matplotlib import dates\n", "from matplotlib import pyplot as plt\n", "\n", "from pyinaturalist import get_observations, get_places_autocomplete\n", "\n", "BASIC_OBS_COLUMNS = [\n", " 'id', 'observed_on', 'location', 'uri', 'taxon.id',\n", " 'taxon.name', 'taxon.rank', 'taxon.preferred_common_name', 'user.login',\n", "]\n", "DATASET_FILENAME = 'midwest_monarchs.json'\n", "PLOT_COLOR = '#fa7b23'\n", "MIDWEST_STATE_IDS = [3, 20, 24, 25, 28, 32, 35, 38] # place_ids of 8 states in the Midwest US\n", "\n", "sns.set_theme(style=\"darkgrid\")" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def date_to_mpl_day_of_year(dt):\n", " \"\"\"Get a matplotlib-compatible date number, ignoring the year (to represent day of year)\"\"\"\n", " try:\n", " return dates.date2num(dt.replace(year=datetime.now().year))\n", " except ValueError:\n", " return None\n", "\n", "def date_to_mpl_time(dt):\n", " \"\"\"Get a matplotlib-compatible date number, ignoring the date (to represent time of day)\"\"\"\n", " try:\n", " return date_to_num(dt) % 1\n", " except ValueError:\n", " return None\n", "\n", "def to_local_tz(dt):\n", " \"\"\"Convert a datetime object to the local time zone\"\"\"\n", " try:\n", " return dt.astimezone(tz.tzlocal())\n", " except (TypeError, ValueError):\n", " return None\n", " \n", "def get_xlim():\n", " \"\"\"Get limits of x axis for first and last days of the year\"\"\"\n", " now = datetime.now()\n", " xmin = dates.date2num(datetime(now.year, 1, 1))\n", " xmax = dates.date2num(datetime(now.year, 12, 31))\n", " return xmin, xmax\n", "\n", "def get_colormap(color):\n", " \"\"\"Make a colormap (gradient) based on the given color; copied from seaborn.axisgrid\"\"\"\n", " color_rgb = mpl.colors.colorConverter.to_rgb(color)\n", " colors = [sns.set_hls_values(color_rgb, l=l) for l in np.linspace(1, 0, 12)]\n", " return sns.blend_palette(colors, as_cmap=True)\n", "\n", "def pdir(obj, sort_types=False, non_callables=False):\n", " attrs = {attr: type(getattr(obj, attr)).__name__ for attr in dir(obj)}\n", " if sort_types:\n", " attrs = {k: v for k, v in sorted(attrs.items(), key=lambda x: x[1])}\n", " if non_callables:\n", " attrs = {k: v for k, v in attrs.items() if v not in ['function', 'method', 'method-wrapper', 'builtin_function_or_method']}\n", " pprint(attrs, sort_dicts=not sort_types)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Get all observations for a given place and species" ] }, { "cell_type": "code", "execution_count": 478, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{24: 'Iowa',\n", " 1911: 'Iowa',\n", " 2840: 'Iowa',\n", " 8680: 'Iowa City',\n", " 119385: 'Iowa Wetland Management District',\n", " 125537: 'Terry Trueblood Wetland Exploration Trail',\n", " 137891: 'Pammel State Park, Winterset, Iowa',\n", " 151098: 'Mount Vernon, Iowa walking path',\n", " 161392: 'Upper Iowa River Wildlife Management Areas',\n", " 172799: 'Ashton Prairie'}\n" ] } ], "source": [ "# Optional: search for a place ID by name\n", "response = get_places_autocomplete(q='iowa')\n", "pprint({p['id']: p['name'] for p in response['results']})" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# TODO: This should be done with the /observations/histogram endpoint instead\n", "\n", "# Optional: reload from previously loaded results, if available\n", "#if exists(DATASET_FILENAME):\n", "# with open(DATASET_FILENAME) as f:\n", "# observations = json.load(f)\n", "#else:\n", "\n", "observations = get_observations(\n", " taxon_name='Danaus plexippus',\n", " photos=True,\n", " geo=True,\n", " geoprivacy='open',\n", " place_id=MIDWEST_STATE_IDS,\n", " page='all',\n", ")\n", "# Save results for future usage\n", "with open(DATASET_FILENAME, 'w') as f:\n", " json.dump(observations, f, indent=4, sort_keys=True, default=str)\n", " \n", "print(f'Total observations: {len(observations)}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data cleanup" ] }, { "cell_type": "code", "execution_count": 453, "metadata": {}, "outputs": [], "source": [ "# Flatten nested JSON values\n", "df = pd.json_normalize(observations)\n", "\n", "# Normalize timezones\n", "df['observed_on'] = df['observed_on'].dropna().apply(to_local_tz)\n", "\n", "# Add some extra date/time columns that matplotlib can more easily handle\n", "df['observed_time_mp'] = df['observed_on'].apply(date_to_mpl_time)\n", "df['observed_on_mp'] = df['observed_on'].apply(date_to_mpl_day_of_year)" ] }, { "cell_type": "code", "execution_count": 397, "metadata": {}, "outputs": [], "source": [ "# Optional: narrow down to just a few columns of interest\n", "#pprint(list(sorted(df.columns)))\n", "#df = df[OBS_COLUMNS]\n", "\n", "# Optional: Hacky way of setting limits by adding outliers\n", "# JointGrid + hexbin doesn't make it easy to do this the 'right' way without distorting the plot\n", "#df2 = pd.DataFrame([\n", "# {'observed_on': datetime(2020, 1, 1, 0, 0, 0, tzinfo=tz.tzlocal()), 'quality_grade': 'research'},\n", "# {'observed_on': datetime(2020, 12, 31, 23, 59, 59, tzinfo=tz.tzlocal()), 'quality_grade': 'research'},\n", "#])\n", "#df = df.append(df2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic seasonality plot: observation counts by month & quality grade" ] }, { "cell_type": "code", "execution_count": 455, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", " | observed_month | \n", "quality_grade | \n", "counts | \n", "
---|---|---|---|
0 | \n", "1.0 | \n", "casual | \n", "3 | \n", "
1 | \n", "3.0 | \n", "casual | \n", "1 | \n", "
2 | \n", "4.0 | \n", "casual | \n", "4 | \n", "
3 | \n", "4.0 | \n", "research | \n", "29 | \n", "
4 | \n", "5.0 | \n", "casual | \n", "2 | \n", "
5 | \n", "5.0 | \n", "research | \n", "309 | \n", "
6 | \n", "6.0 | \n", "casual | \n", "20 | \n", "
7 | \n", "6.0 | \n", "research | \n", "1479 | \n", "
8 | \n", "7.0 | \n", "casual | \n", "21 | \n", "
9 | \n", "7.0 | \n", "needs_id | \n", "2 | \n", "
10 | \n", "7.0 | \n", "research | \n", "3325 | \n", "
11 | \n", "8.0 | \n", "casual | \n", "27 | \n", "
12 | \n", "8.0 | \n", "needs_id | \n", "3 | \n", "
13 | \n", "8.0 | \n", "research | \n", "3772 | \n", "
14 | \n", "9.0 | \n", "casual | \n", "34 | \n", "
15 | \n", "9.0 | \n", "needs_id | \n", "6 | \n", "
16 | \n", "9.0 | \n", "research | \n", "3023 | \n", "
17 | \n", "10.0 | \n", "casual | \n", "6 | \n", "
18 | \n", "10.0 | \n", "research | \n", "652 | \n", "
19 | \n", "11.0 | \n", "casual | \n", "5 | \n", "
20 | \n", "11.0 | \n", "research | \n", "23 | \n", "
21 | \n", "12.0 | \n", "research | \n", "6 | \n", "