{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n.. redirect-from:: /tutorials/colors/colors\n\n\n# Specifying colors\n\n## Color formats\n\nMatplotlib recognizes the following formats to specify a color.\n\n+--------------------------------------+--------------------------------------+\n| Format | Example |\n+======================================+======================================+\n| RGB or RGBA (red, green, blue, alpha)| - ``(0.1, 0.2, 0.5)`` |\n| tuple of float values in a closed | - ``(0.1, 0.2, 0.5, 0.3)`` |\n| interval [0, 1]. | |\n+--------------------------------------+--------------------------------------+\n| Case-insensitive hex RGB or RGBA | - ``'#0f0f0f'`` |\n| string. | - ``'#0f0f0f80'`` |\n+--------------------------------------+--------------------------------------+\n| Case-insensitive RGB or RGBA string | - ``'#abc'`` as ``'#aabbcc'`` |\n| equivalent hex shorthand of | - ``'#fb1'`` as ``'#ffbb11'`` |\n| duplicated characters. | |\n+--------------------------------------+--------------------------------------+\n| String representation of float value | - ``'0'`` as black |\n| in closed interval ``[0, 1]`` for | - ``'1'`` as white |\n| grayscale values. | - ``'0.8'`` as light gray |\n+--------------------------------------+--------------------------------------+\n| Single character shorthand notation | - ``'b'`` as blue |\n| for some basic colors. | - ``'g'`` as green |\n| | - ``'r'`` as red |\n| .. note:: | - ``'c'`` as cyan |\n| The colors green, cyan, magenta, | - ``'m'`` as magenta |\n| and yellow do not coincide with | - ``'y'`` as yellow |\n| X11/CSS4 colors. Their particular | - ``'k'`` as black |\n| shades were chosen for better | - ``'w'`` as white |\n| visibility of colored lines | |\n| against typical backgrounds. | |\n+--------------------------------------+--------------------------------------+\n| Case-insensitive X11/CSS4 color name | - ``'aquamarine'`` |\n| with no spaces. | - ``'mediumseagreen'`` |\n+--------------------------------------+--------------------------------------+\n| Case-insensitive color name from | - ``'xkcd:sky blue'`` |\n| `xkcd color survey`_ with ``'xkcd:'``| - ``'xkcd:eggshell'`` |\n| prefix. | |\n+--------------------------------------+--------------------------------------+\n| Case-insensitive Tableau Colors from | - ``'tab:blue'`` |\n| 'T10' categorical palette. | - ``'tab:orange'`` |\n| | - ``'tab:green'`` |\n| | - ``'tab:red'`` |\n| | - ``'tab:purple'`` |\n| .. note:: This is the default color | - ``'tab:brown'`` |\n| cycle. | - ``'tab:pink'`` |\n| | - ``'tab:gray'`` |\n| | - ``'tab:olive'`` |\n| | - ``'tab:cyan'`` |\n+--------------------------------------+--------------------------------------+\n| \"CN\" color spec where ``'C'`` | - ``'C0'`` |\n| precedes a number acting as an index | - ``'C1'`` |\n| into the default property cycle. +--------------------------------------+\n| | :rc:`axes.prop_cycle` |\n| .. note:: Matplotlib indexes color | |\n| at draw time and defaults | |\n| to black if cycle does not | |\n| include color. | |\n+--------------------------------------+--------------------------------------+\n| Tuple of one of the above color | - ``('green', 0.3)`` |\n| formats and an alpha float. | - ``('#f00', 0.9)`` |\n| | |\n| .. versionadded:: 3.8 | |\n+--------------------------------------+--------------------------------------+\n| The special value \"none\" is fully | - ``'none'`` |\n| transparent, i.e. equivalent to a | |\n| RGBA value ``(0.0, 0.0, 0.0, 0.0)`` | |\n+--------------------------------------+--------------------------------------+\n\n\n.. seealso::\n\n The following links provide more information on colors in Matplotlib.\n * :doc:`/gallery/color/color_demo` Example\n * `matplotlib.colors` API\n * :doc:`/gallery/color/named_colors` Example\n\n\"Red\", \"Green\", and \"Blue\" are the intensities of those colors. In combination,\nthey represent the colorspace.\n\n## Transparency\n\nThe *alpha* value of a color specifies its transparency, where 0 is fully\ntransparent and 1 is fully opaque. When a color is semi-transparent, the\nbackground color will show through.\n\nThe *alpha* value determines the resulting color by blending the\nforeground color with the background color according to the formula\n\n\\begin{align}RGB_{result} = RGB_{background} * (1 - \\alpha) + RGB_{foreground} * \\alpha\\end{align}\n\nThe following plot illustrates the effect of transparency.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.patches import Rectangle\n\nfig, ax = plt.subplots(figsize=(6.5, 1.65), layout='constrained')\nax.add_patch(Rectangle((-0.2, -0.35), 11.2, 0.7, color='C1', alpha=0.8))\nfor i, alpha in enumerate(np.linspace(0, 1, 11)):\n ax.add_patch(Rectangle((i, 0.05), 0.8, 0.6, alpha=alpha, zorder=0))\n ax.text(i+0.4, 0.85, f\"{alpha:.1f}\", ha='center')\n ax.add_patch(Rectangle((i, -0.05), 0.8, -0.6, alpha=alpha, zorder=2))\nax.set_xlim(-0.2, 13)\nax.set_ylim(-1, 1)\nax.set_title('alpha values')\nax.text(11.3, 0.6, 'zorder=1', va='center', color='C0')\nax.text(11.3, 0, 'zorder=2\\nalpha=0.8', va='center', color='C1')\nax.text(11.3, -0.6, 'zorder=3', va='center', color='C0')\nax.axis('off')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The orange rectangle is semi-transparent with *alpha* = 0.8. The top row of\nblue squares is drawn below and the bottom row of blue squares is drawn on\ntop of the orange rectangle.\n\nSee also :doc:`/gallery/misc/zorder_demo` to learn more on the drawing order.\n\n\n## \"CN\" color selection\n\nMatplotlib converts \"CN\" colors to RGBA when drawing Artists. The\n`color_cycle` section contains additional\ninformation about controlling colors and style properties.\n\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\nth = np.linspace(0, 2*np.pi, 128)\n\n\ndef demo(sty):\n mpl.style.use(sty)\n fig, ax = plt.subplots(figsize=(3, 3))\n\n ax.set_title(f'style: {sty!r}', color='C0')\n\n ax.plot(th, np.cos(th), 'C1', label='C1')\n ax.plot(th, np.sin(th), 'C2', label='C2')\n ax.legend()\n\n\ndemo('default')\ndemo('seaborn-v0_8')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first color ``'C0'`` is the title. Each plot uses the second and third\ncolors of each style's :rc:`axes.prop_cycle`. They are ``'C1'`` and ``'C2'``,\nrespectively.\n\n\n## Comparison between X11/CSS4 and xkcd colors\n\nThe xkcd colors come from a [user survey conducted by the webcomic xkcd](https://blog.xkcd.com/2010/05/03/color-survey-results/)_.\n\n95 out of the 148 X11/CSS4 color names also appear in the xkcd color survey.\nAlmost all of them map to different color values in the X11/CSS4 and in\nthe xkcd palette. Only 'black', 'white' and 'cyan' are identical.\n\nFor example, ``'blue'`` maps to ``'#0000FF'`` whereas ``'xkcd:blue'`` maps to\n``'#0343DF'``. Due to these name collisions, all xkcd colors have the\n``'xkcd:'`` prefix.\n\nThe visual below shows name collisions. Color names where color values agree\nare in bold.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.colors as mcolors\nimport matplotlib.patches as mpatch\n\noverlap = {name for name in mcolors.CSS4_COLORS\n if f'xkcd:{name}' in mcolors.XKCD_COLORS}\n\nfig = plt.figure(figsize=[9, 5])\nax = fig.add_axes([0, 0, 1, 1])\n\nn_groups = 3\nn_rows = len(overlap) // n_groups + 1\n\nfor j, color_name in enumerate(sorted(overlap)):\n css4 = mcolors.CSS4_COLORS[color_name]\n xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()\n\n # Pick text colour based on perceived luminance.\n rgba = mcolors.to_rgba_array([css4, xkcd])\n luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]\n css4_text_color = 'k' if luma[0] > 0.5 else 'w'\n xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'\n\n col_shift = (j // n_rows) * 3\n y_pos = j % n_rows\n text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)\n ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))\n ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))\n ax.text(0.5 + col_shift, y_pos + .7, css4,\n color=css4_text_color, ha='center', **text_args)\n ax.text(1.5 + col_shift, y_pos + .7, xkcd,\n color=xkcd_text_color, ha='center', **text_args)\n ax.text(2 + col_shift, y_pos + .7, f' {color_name}', **text_args)\n\nfor g in range(n_groups):\n ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)\n ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')\n ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')\n\nax.set_xlim(0, 3 * n_groups)\nax.set_ylim(n_rows, -1)\nax.axis('off')\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.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }