{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "
\n", "\"Unidata\n", "
\n", "\n", "

Matplotlib: Intermediate

\n", "

Unidata AMS 2021 Student Conference

\n", "\n", "
\n", "
\n", "\n", "---\n", "\n", "
\"Colorized
\n", "\n", "\n", "### Focuses\n", "\n", "* Draw multiple plots in the same figure.\n", "* Colorize individual scatter plot points based on some criteria.\n", "* Use imshow, contour and contourf to draw a heat maps and contour plots.\n", "\n", "\n", "### Objectives\n", "\n", "1. [Create Test Data](#1.-Create-Test-Data)\n", "1. [Multiple Plots on One Figure](#2.-Multiple-Plots-on-One-Figure)\n", "1. [Colorizing Scatter Plots](#3.-Colorizing-Scatter-Plots)\n", "1. [Plot a Heat Map with Imshow](#4.-Plot-a-Heat-Map-with-Imshow)\n", "1. [Plot with Contour](#5.-Plot-with-Contour)\n", "1. [Plot with Contourf](#6.-Plot-with-Contourf)\n", "1. [Combine Imshow and Contour](#7.-Combine-Imshow-and-Contour)\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Imports" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Create Test Data\n", "\n", "First, instantiate some test data to work with in this notebook." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create the test data to work with\n", "times = np.array([ 93., 96., 99., 102., 105., 108., 111., 114., 117.,\n", " 120., 123., 126., 129., 132., 135., 138., 141., 144.,\n", " 147., 150., 153., 156., 159., 162.])\n", "temps = np.array([310.7, 308.0, 296.4, 289.5, 288.5, 287.1, 301.1, 308.3,\n", " 311.5, 305.1, 295.6, 292.4, 290.4, 289.1, 299.4, 307.9,\n", " 316.6, 293.9, 291.2, 289.8, 287.1, 285.8, 303.3, 310.])\n", "temps_1000 = np.array([316.0, 316.3, 308.9, 304.0, 302.0, 300.8, 306.2, 309.8,\n", " 313.5, 313.3, 308.3, 304.9, 301.0, 299.2, 302.6, 309.0,\n", " 311.8, 304.7, 304.6, 301.8, 300.6, 299.9, 306.3, 311.3])\n", "# Fake dewpoint data to plot\n", "dewpoint = 0.9 * temps\n", "dewpoint_1000 = 0.9 * temps_1000" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Top\n", "\n", "---\n", "\n", "## 2. Multiple Plots on One Figure\n", "\n", "The [Matplotlib: Basics notebook](https://nbviewer.jupyter.org/github/Unidata/pyaos-ams-2021/blob/master/notebooks/visualization/matplotlib-basics.ipynb) explained how to create a figure and add a plot to that figure. It is also possible to add multiple plots to the same figure. In this step, a figure is first created and then multiple plots are added, each with their own titles, axes, etc. Each plot is added using the *add_subplot()* function, which lays out multiple plots in a grid by passing the number of rows, columns, and which plot within the grid (starting with 1, not 0).\n", "> So for example, if you wanted to create a plot in the lower left corner of a (hypothetical) grid of plots with 2 rows and 3 columns, you could write fig.add_subplot(2, 3, 4), where 4 means the 4th plot, counting across rows and down columns.\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Cell content replaced by load magic replacement.\n", "fig = plt.figure(figsize=(10, 6))\n", "ax = fig.add_subplot(1, 2, 1)\n", "\n", "# Specify how our lines should look\n", "ax.plot(times, temps, color='tab:red', label='Temperature (surface)')\n", "ax.plot(times, temps_1000, color='tab:red', linestyle=':',\n", " label='Temperature (isobaric level)')\n", "\n", "# Add labels, title, and display settings\n", "ax.set_xlabel('Time')\n", "ax.set_ylabel('Temperature')\n", "ax.set_title('Temperature Forecast')\n", "ax.grid(True)\n", "ax.legend(loc='upper left')\n", "\n", "# Create the second plot\n", "ax2 = fig.add_subplot(1, 2, 2, sharex=ax, sharey=ax)\n", "ax2.plot(times, dewpoint, color='tab:green', label='Dewpoint (surface)')\n", "ax2.plot(times, dewpoint_1000, color='tab:green', linestyle=':', marker='o',\n", " label='Dewpoint (isobaric level)')\n", "\n", "# Add labels, title, and display settings\n", "ax2.set_xlabel('Time')\n", "ax2.set_ylabel('Dewpoint')\n", "ax2.set_title('Dewpoint Forecast')\n", "ax2.grid(True)\n", "ax2.legend(loc='upper left')\n", "ax2.set_ylim(257, 312)\n", "ax2.set_xlim(95, 162)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Top\n", "\n", "---\n", "\n", "## 3. Colorizing Scatter Plots\n", "\n", "Previously, in the [Matplotlib: Basics notebook](https://nbviewer.jupyter.org/github/Unidata/pyaos-ams-2021/blob/master/notebooks/visualization/matplotlib-basics.ipynb), an example for drawing scatter plots was provided by setting the **linestyle** to none, and adding 'o' markers. Another alternative is to use the **scatter** methods, while these are slower, they allow more visualization options of the data, such as style or color of the individual markers. In this case, the data points will be colorized individually based upon a third variable." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create the plot\n", "fig = plt.figure(figsize=(10, 6))\n", "ax = fig.add_subplot(1, 1, 1)\n", "\n", "# From the axes, get the scatter and set the display parameters\n", "ax.plot([285, 320], [285, 320], color='black', linestyle='--')\n", "s = ax.scatter(temps, temps_1000, c= temps - temps_1000, cmap='bwr', vmin=-5, vmax=5)\n", "fig.colorbar(s)\n", "\n", "# Add labels, title, and gridlines\n", "ax.set_xlabel('Temperature (surface)')\n", "ax.set_ylabel('Temperature (1000 hPa)')\n", "ax.set_title('Temperature Cross Plot')\n", "ax.grid(True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Top\n", "\n", "---\n", "\n", "## 4. Plot a Heat Map with Imshow\n", "\n", "Switching up context now, we can take a look at a different style of plotting. Three other functions called: **imshow**, **contour**, and **contourf** can be used to create different plots.\n", "\n", "**imshow** displays the values in an array as colored pixels, similar to a map." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create some data to work with\n", "x = y = np.arange(-3.0, 3.0, 0.025)\n", "X, Y = np.meshgrid(x, y)\n", "Z1 = np.exp(-X**2 - Y**2)\n", "Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n", "Z = (Z1 - Z2) * 2\n", "\n", "# Create a simple imshow plot\n", "fig, ax = plt.subplots()\n", "im = ax.imshow(Z, interpolation='bilinear', cmap='RdYlGn', origin='lower', extent=[-3, 3, -3, 3])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Top\n", "\n", "---\n", "\n", "## 5. Plot with Contour\n", "\n", "**contour** creates contours around the data." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create one figure for two plots\n", "fig = plt.figure(figsize=(15,6))\n", "\n", "# Create a simple contour\n", "ax = fig.add_subplot(1, 2, 1)\n", "ax.contour(X, Y, Z)\n", "\n", "# Create a second contour with labels\n", "ax2 = fig.add_subplot(1, 2, 2, sharex=ax, sharey=ax)\n", "c = ax2.contour(X, Y, Z, levels=np.arange(-2, 2, 0.25))\n", "ax2.clabel(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Top\n", "\n", "---\n", "\n", "## 6. Plot with Contourf\n", "\n", "**contourf** creates filled contours around data." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "c = ax.contourf(X, Y, Z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Top\n", "\n", "---\n", "\n", "## 7. Combine Imshow and Contour\n", "\n", "Create a figure using imshow and contour that is a heatmap in the colormap of your choice. Overlay black contours with a 0.5 contour interval." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Cell content replaced by load magic replacement.\n", "fig, ax = plt.subplots()\n", "im = ax.imshow(Z, interpolation='bilinear', cmap='PiYG', origin='lower', extent=[-3, 3, -3, 3])\n", "c = ax.contour(X, Y, Z, levels=np.arange(-2, 2, 0.5), colors='black')\n", "ax.clabel(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Top\n", "\n", "---\n", "\n", "## See also\n", "\n", "Documentation for:\n", "\n", "* [matplotlib.pyplot](https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.html)\n", "* [matplotlib.pyplot.figure](https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.figure.html)\n", "* [matplotlib.pyplot.axes](https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.axes.html)\n", "* [matplotlib.pyplot.imshow](https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.imshow.html)\n", "* [matplotlib.pyplot.contour](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.contour.html)\n", "* [matplotlib.pyplot.contourf](https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.contourf.html)\n", "\n", "\n", "### Related Notebooks\n", "\n", "* [Matplotlib: Basics](https://nbviewer.jupyter.org/github/Unidata/pyaos-ams-2021/blob/master/notebooks/visualization/matplotlib-basics.ipynb)\n", "\n", "\n", "Top" ] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:pyaos-ams-2021]", "language": "python", "name": "conda-env-pyaos-ams-2021-py" }, "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.1" } }, "nbformat": 4, "nbformat_minor": 4 }