{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Hillshading\n\nDemonstrates a few common tricks with shaded plots.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.colors import LightSource, Normalize\n\n\ndef display_colorbar():\n \"\"\"Display a correct numeric colorbar for a shaded plot.\"\"\"\n y, x = np.mgrid[-4:2:200j, -4:2:200j]\n z = 10 * np.cos(x**2 + y**2)\n\n cmap = plt.cm.copper\n ls = LightSource(315, 45)\n rgb = ls.shade(z, cmap)\n\n fig, ax = plt.subplots()\n ax.imshow(rgb, interpolation='bilinear')\n\n # Use a proxy artist for the colorbar...\n im = ax.imshow(z, cmap=cmap)\n im.remove()\n fig.colorbar(im, ax=ax)\n\n ax.set_title('Using a colorbar with a shaded plot', size='x-large')\n\n\ndef avoid_outliers():\n \"\"\"Use a custom norm to control the displayed z-range of a shaded plot.\"\"\"\n y, x = np.mgrid[-4:2:200j, -4:2:200j]\n z = 10 * np.cos(x**2 + y**2)\n\n # Add some outliers...\n z[100, 105] = 2000\n z[120, 110] = -9000\n\n ls = LightSource(315, 45)\n fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4.5))\n\n rgb = ls.shade(z, plt.cm.copper)\n ax1.imshow(rgb, interpolation='bilinear')\n ax1.set_title('Full range of data')\n\n rgb = ls.shade(z, plt.cm.copper, vmin=-10, vmax=10)\n ax2.imshow(rgb, interpolation='bilinear')\n ax2.set_title('Manually set range')\n\n fig.suptitle('Avoiding Outliers in Shaded Plots', size='x-large')\n\n\ndef shade_other_data():\n \"\"\"Demonstrates displaying different variables through shade and color.\"\"\"\n y, x = np.mgrid[-4:2:200j, -4:2:200j]\n z1 = np.sin(x**2) # Data to hillshade\n z2 = np.cos(x**2 + y**2) # Data to color\n\n norm = Normalize(z2.min(), z2.max())\n cmap = plt.cm.RdBu\n\n ls = LightSource(315, 45)\n rgb = ls.shade_rgb(cmap(norm(z2)), z1)\n\n fig, ax = plt.subplots()\n ax.imshow(rgb, interpolation='bilinear')\n ax.set_title('Shade by one variable, color by another', size='x-large')\n\ndisplay_colorbar()\navoid_outliers()\nshade_other_data()\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.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }