{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Histogram as colorbar\n\nThis example demonstrates how to use a colored histogram instead of a colorbar\nto not only show the color-to-value mapping, but also visualize the\ndistribution of values.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib.colors as mcolors\n\n# surface data\ndelta = 0.025\nx = y = np.arange(-2.0, 2.0, delta)\nX, Y = np.meshgrid(x, y)\nZ1 = np.exp(-(((X + 1) * 1.3) ** 2) - ((Y + 1) * 1.3) ** 2)\nZ2 = 2.5 * np.exp(-((X - 1) ** 2) - (Y - 1) ** 2)\nZ = Z1**0.25 - Z2**0.5\n\n# colormap & normalization\nbins = 30\ncmap = plt.get_cmap(\"RdYlBu_r\")\nbin_edges = np.linspace(Z.min(), Z.max(), bins + 1)\nnorm = mcolors.BoundaryNorm(bin_edges, cmap.N)\n\n# main plot\nfig, ax = plt.subplots(layout=\"constrained\")\nim = ax.imshow(Z, cmap=cmap, origin=\"lower\", extent=[-3, 3, -3, 3], norm=norm)\n\n# inset histogram\ncax = ax.inset_axes([1.18, 0.02, 0.25, 0.95]) # left, bottom, width, height\n\n# plot histogram\ncounts, _ = np.histogram(Z, bins=bin_edges)\nmidpoints = (bin_edges[:-1] + bin_edges[1:]) / 2\ndistance = midpoints[1] - midpoints[0]\ncax.barh(midpoints, counts, height=0.8 * distance, color=cmap(norm(midpoints)))\n\n# styling\ncax.spines[:].set_visible(False)\ncax.set_yticks(bin_edges)\ncax.tick_params(axis=\"both\", which=\"both\", length=0)\n\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.12.15" } }, "nbformat": 4, "nbformat_minor": 0 }