{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Matplotlib interactive examples\n", "\n", "This is a small example of using Matplotlib for interactive data visualization. \n", "\n", "To get interactive visualization you must \"run\" the notebook cells (in order). You can hit the \"play\" triangle above, or the \"play-all\" double triangle to run all the cells, or select a cell and hit \"Shift-Enter\". Once active, you can zoom and pan in the provided data using the GUI toolbar at left of each figure." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "# this sets up the Matplotlib interactive windows:\n", "%matplotlib widget\n", "\n", "# this changes the default date converter for better interactive plotting of dates:\n", "plt.rcParams['date.converter'] = 'concise'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Time series example: temperature at Dinosaur, Co\n", "\n", "Data is from https://www.ncei.noaa.gov/pub/data/uscrn/products/hourly02/ and is hourly temperature and solar radiation at Dinosaur, Colorado.\n", "\n", "### Load the data" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# Note the use of datetimes in the file complicate loading a bit.\n", "# We recommend using pandas or xarray for more elegant solutions\n", "# to handling complex timeseries data. \n", "with open('data/small.txt', 'r') as f:\n", " data = np.genfromtxt(f, dtype='datetime64[s],f,f,f', \n", " names=['date', 'doy', 'temp', 'solar'])\n", "datetime = data['date']\n", "dayofyear = data['doy']\n", "temperature = data['temp']\n", "solar = data['solar']\n", "\n", "# make two-day smoothed versions:\n", "temp_low = np.convolve(temperature, np.ones(48)/48, mode='same')\n", "solar_low = np.convolve(solar, np.ones(48)/48, mode='same')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plot timeseries\n", "\n", "Here we plot the time series, add labels, title, and a small annotation about where the data came from. Using the toolbar on the left you can zoom in on the data to see, for instance, the day/night warming and cooling. You can also pan along the time series using the icon with four arrows. Note that because we have said `sharex=True` when creating the axes, the time window remains connected in both time seroes." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "2986d273194e4c66b6bcec4c2c21110f", "version_major": 2, "version_minor": 0 }, "text/html": [ "\n", "
\n", "
\n", " Figure\n", "
\n", " \n", "
\n", " " ], "text/plain": [ "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "fig, (ax0, ax1) = plt.subplots(2, 1, sharex=True, constrained_layout=True)\n", "\n", "# temperature:\n", "ax0.plot(datetime, temperature, label='hourly')\n", "ax0.plot(datetime, temp_low, label='smoothed')\n", "ax0.legend(loc='upper right')\n", "ax0.set_ylabel('Temperature $[^oC]$') # note the use of TeX math formatting\n", "\n", "# solar-radiation:\n", "ax1.plot(datetime, solar, label='hourly')\n", "ax1.plot(datetime, solar_low, label='smoothed')\n", "ax1.legend(loc='upper right')\n", "ax1.set_ylabel('Solar radiation $[W\\,m^{-2}]$') # note the use of TeX math formatting\n", "\n", "ax0.set_title('Observations: Dinosaur, Colorado', loc='left')\n", "ax0.text(0.03, 0.03, 'https://www.ncei.noaa.gov/pub/data/uscrn/products/hourly02/', \n", " fontsize='small', fontstyle='italic', transform=ax0.transAxes);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plot property-versus-property\n", "\n", "Lets make a scatter plot of solar radiation versus temperature, colored by day of the year. Note that we do not share the axes this time because the dynamic range of the hourly and smoothed data is different." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "a085dc7d4b9b4d8baa092ba0e2d69bd3", "version_major": 2, "version_minor": 0 }, "text/html": [ "\n", "
\n", "
\n", " Figure\n", "
\n", " \n", "
\n", " " ], "text/plain": [ "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "fig, [ax0, ax1] = plt.subplots(1, 2, constrained_layout=True, figsize=(8, 4))\n", "\n", "ax0.set_facecolor('0.6')\n", "sc = ax0.scatter(solar, temperature, c=dayofyear, s=2, cmap='RdBu_r')\n", "ax0.set_xlabel('Solar Radiation $[W\\,m^{-2}]$')\n", "ax0.set_ylabel('Temperature $[^oC]$')\n", "ax0.set_title('Hourly', loc='left')\n", "\n", "\n", "ax1.set_facecolor('0.6')\n", "sc = ax1.scatter(solar_low[::24], temp_low[::24], c=dayofyear[::24], s=4, cmap='RdBu_r')\n", "ax1.set_xlabel('Solar Radiation $[W\\,m^{-2}]$')\n", "ax1.set_ylabel('Temperature $[^oC]$')\n", "ax1.set_title('Smoothed', loc='left')\n", "\n", "fig.colorbar(sc, ax=[ax0, ax1], shrink=0.6, label='day of year')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Image data: global land-surface temperature\n", "\n", "Matplotlib can also plot two-dimensional data as in this example of land surface temperature. Note that for geographic data a package like cartopy or metpy is recommended. \n", "\n", "### Load the data" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "dat = np.genfromtxt('data/MOD_LSTD_E_2021-08-29_gs_720x360.CSV', delimiter=',')\n", "dat = np.where(dat<1000, dat, np.NaN)\n", "dat = dat[::-1, :]\n", "lon = np.arange(-180.0, 180.1, 0.5)\n", "lat = np.arange(-90.0, 90.1, 0.5)\n", "date = '2021-08-29 to 2021-09-05'\n", "source = 'https://neo.sci.gsfc.nasa.gov/view.php?datasetId=MOD_LSTD_E&date=2021-09-01'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plot data" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "bdb66b934b05437cb0f3552ae645c0b9", "version_major": 2, "version_minor": 0 }, "text/html": [ "\n", "
\n", "
\n", " Figure\n", "
\n", " \n", "
\n", " " ], "text/plain": [ "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "fig, ax = plt.subplots(constrained_layout=True, figsize=(7, 4))\n", "ax.set_facecolor('0.8')\n", "pc = ax.pcolormesh(lon, lat, dat, shading='auto', cmap='inferno')\n", "ax.set_aspect(1.3)\n", "ax.set_xlabel('Longitude $[^o E]$')\n", "ax.set_ylabel('Latitude $[^o N]$')\n", "fig.colorbar(pc, shrink=0.6, extend='both', label='land temperature $[^oC]$');\n", "ax.set_title(f'source: {source}', loc='left', fontsize='x-small');" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "jupytext": { "formats": "ipynb,md" }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.7" }, "toc-showmarkdowntxt": false }, "nbformat": 4, "nbformat_minor": 4 }