{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Selecting individual colors from a colormap\n\nSometimes we want to use more colors or a different set of colors than the default color\ncycle provides. Selecting individual colors from one of the provided colormaps can be a\nconvenient way to do this.\n\nWe can retrieve colors from any `.Colormap` by calling it with a float or a list of\nfloats in the range [0, 1]; e.g. ``cmap(0.5)`` will give the middle color. See also\n`.Colormap.__call__`.\n\n## Extracting colors from a continuous colormap\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib as mpl\n\nn_lines = 21\ncmap = mpl.colormaps['plasma']\n\n# Take colors at regular intervals spanning the colormap.\ncolors = cmap(np.linspace(0, 1, n_lines))\n\nfig, ax = plt.subplots(layout='constrained')\n\nfor i, color in enumerate(colors):\n ax.plot([0, i], color=color)\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Extracting colors from a discrete colormap\nThe list of all colors in a `.ListedColormap` is available as the ``colors``\nattribute. Note that all the colors from Matplotlib's qualitative color maps\nare also available as color sequences, so may be accessed more directly from\nthe color sequence registry. See :doc:`/gallery/color/color_sequences`.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors = mpl.colormaps['Dark2'].colors\n\nfig, ax = plt.subplots(layout='constrained')\n\nfor i, color in enumerate(colors):\n ax.plot([0, i], color=color)\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## See Also\n\nFor more details about manipulating colormaps, see `colormap-manipulation`. To\nchange the default color cycle, see `color_cycle`.\n\n.. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.colors.Colormap`\n - `matplotlib.colors.Colormap.resampled`\n\n.. tags::\n\n component: colormap\n styling: color\n plot-type: line\n level: intermediate\n\n" ] } ], "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.5" } }, "nbformat": 4, "nbformat_minor": 0 }