Colors in python matplotlib

matplotlib.colors #

The Color tutorials and examples demonstrate how to set colors and colormaps. You may want to read those instead.

A module for converting numbers or color arguments to RGB or RGBA.

RGB and RGBA are sequences of, respectively, 3 or 4 floats in the range 0-1.

This module includes functions and classes for color specification conversions, and for mapping numbers to colors in a 1-D array of colors called a colormap.

Mapping data onto colors using a colormap typically involves two steps: a data array is first mapped onto the range 0-1 using a subclass of Normalize , then this number is mapped to a color using a subclass of Colormap . Two subclasses of Colormap provided here: LinearSegmentedColormap , which uses piecewise-linear interpolation to define colormaps, and ListedColormap , which makes a colormap from a list of colors.

Creating Colormaps in Matplotlib for examples of how to make colormaps and

Colormap Normalization for more details about data normalization

More colormaps are available at palettable.

The module also provides functions for checking whether an object can be interpreted as a color ( is_color_like ), for converting such an object to an RGBA tuple ( to_rgba ) or to an HTML-like hex string in the «#rrggbb» format ( to_hex ), and a sequence of colors to an (n, 4) RGBA array ( to_rgba_array ). Caching is used for efficiency.

Colors that Matplotlib recognizes are listed at Specifying colors .

Color norms#

A class which, when called, linearly normalizes data into the [0.0, 1.0] interval.

Dummy replacement for Normalize , for the case where we want to use indices directly in a ScalarMappable .

AsinhNorm ([linear_width, vmin, vmax, clip])

The inverse hyperbolic sine scale is approximately linear near the origin, but becomes logarithmic for larger positive or negative values.

BoundaryNorm (boundaries, ncolors[, clip, extend])

Generate a colormap index based on discrete intervals.

Normalize symmetrical data around a center (0 by default).

Arbitrary normalization using functions for the forward and inverse.

Normalize a given value to the 0-1 range on a log scale.

Linearly map a given value to the 0-1 range and then apply a power-law normalization over that range.

The symmetrical logarithmic scale is logarithmic in both the positive and negative directions from the origin.

Normalize data with a set center.

Colormaps#

Baseclass for all scalar to RGBA mappings.

Colormap objects based on lookup tables using linear segments.

Colormap object generated from a list of colors.

Other classes#

Container for sequences of colors that are known to Matplotlib by name.

Create a light source coming from the specified azimuth and elevation.

Functions#

A helper routine to generate a cmap and a norm instance which behave similar to contourf’s levels and colors arguments.

Convert HSV values to RGB.

Convert float RGB values (in the range [0, 1]), in a numpy array to HSV values.

Convert c to an RGB color, silently dropping the alpha channel.

Convert c to an RGBA color.

Convert c to a (n, 4) array of RGBA colors.

Return whether c can be interpreted as an RGB(A) color.

Return whether the colors c1 and c2 are the same.

Return the global mapping of names to named colors.

Decorator for building a Normalize subclass from a ScaleBase subclass.

Exported colors#

The data used to populate the List of named colors are exposed as dictionaries that map color names to hex strings.

matplotlib.colors. BASE_COLORS # matplotlib.colors. TABLEAU_COLORS # matplotlib.colors. CSS4_COLORS # matplotlib.colors. XKCD_COLORS #

© Copyright 2002–2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012–2023 The Matplotlib development team.

Built from v3.7.2-2-g4915f574b8.

Источник

List of named colors#

First we define a helper function for making a table of colors, then we use it on some common color categories.

import math from matplotlib.patches import Rectangle import matplotlib.pyplot as plt import matplotlib.colors as mcolors def plot_colortable(colors, *, ncols=4, sort_colors=True): cell_width = 212 cell_height = 22 swatch_width = 48 margin = 12 # Sort colors by hue, saturation, value and name. if sort_colors is True: names = sorted( colors, key=lambda c: tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(c)))) else: names = list(colors) n = len(names) nrows = math.ceil(n / ncols) width = cell_width * 4 + 2 * margin height = cell_height * nrows + 2 * margin dpi = 72 fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi) fig.subplots_adjust(margin/width, margin/height, (width-margin)/width, (height-margin)/height) ax.set_xlim(0, cell_width * 4) ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.) ax.yaxis.set_visible(False) ax.xaxis.set_visible(False) ax.set_axis_off() for i, name in enumerate(names): row = i % nrows col = i // nrows y = row * cell_height swatch_start_x = cell_width * col text_pos_x = cell_width * col + swatch_width + 7 ax.text(text_pos_x, y, name, fontsize=14, horizontalalignment='left', verticalalignment='center') ax.add_patch( Rectangle(xy=(swatch_start_x, y-9), width=swatch_width, height=18, facecolor=colors[name], edgecolor='0.7') ) return fig 

Base colors#

named colors

Tableau Palette#

Источник

Specifying colors#

Matplotlib recognizes the following formats to specify a color.

RGB or RGBA (red, green, blue, alpha) tuple of float values in a closed interval [0, 1].

Case-insensitive hex RGB or RGBA string.

Case-insensitive RGB or RGBA string equivalent hex shorthand of duplicated characters.

String representation of float value in closed interval [0, 1] for grayscale values.

Single character shorthand notation for some basic colors.

The colors green, cyan, magenta, and yellow do not coincide with X11/CSS4 colors. Their particular shades were chosen for better visibility of colored lines against typical backgrounds.

  • ‘b’ as blue
  • ‘g’ as green
  • ‘r’ as red
  • ‘c’ as cyan
  • ‘m’ as magenta
  • ‘y’ as yellow
  • ‘k’ as black
  • ‘w’ as white

Case-insensitive X11/CSS4 color name with no spaces.

Case-insensitive color name from xkcd color survey with ‘xkcd:’ prefix.

Case-insensitive Tableau Colors from ‘T10’ categorical palette.

This is the default color cycle.

  • ‘tab:blue’
  • ‘tab:orange’
  • ‘tab:green’
  • ‘tab:red’
  • ‘tab:purple’
  • ‘tab:brown’
  • ‘tab:pink’
  • ‘tab:gray’
  • ‘tab:olive’
  • ‘tab:cyan’

«CN» color spec where ‘C’ precedes a number acting as an index into the default property cycle.

Matplotlib indexes color at draw time and defaults to black if cycle does not include color.

rcParams[«axes.prop_cycle»] (default: cycler(‘color’, [‘#1f77b4’, ‘#ff7f0e’, ‘#2ca02c’, ‘#d62728’, ‘#9467bd’, ‘#8c564b’, ‘#e377c2’, ‘#7f7f7f’, ‘#bcbd22’, ‘#17becf’]) )

«Red», «Green», and «Blue» are the intensities of those colors. In combination, they represent the colorspace.

Transparency#

The alpha value of a color specifies its transparency, where 0 is fully transparent and 1 is fully opaque. When a color is semi-transparent, the background color will show through.

The alpha value determines the resulting color by blending the foreground color with the background color according to the formula

The following plot illustrates the effect of transparency.

import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import numpy as np fig, ax = plt.subplots(figsize=(6.5, 1.65), layout='constrained') ax.add_patch(Rectangle((-0.2, -0.35), 11.2, 0.7, color='C1', alpha=0.8)) for i, alpha in enumerate(np.linspace(0, 1, 11)): ax.add_patch(Rectangle((i, 0.05), 0.8, 0.6, alpha=alpha, zorder=0)) ax.text(i+0.4, 0.85, f"alpha:.1f>", ha='center') ax.add_patch(Rectangle((i, -0.05), 0.8, -0.6, alpha=alpha, zorder=2)) ax.set_xlim(-0.2, 13) ax.set_ylim(-1, 1) ax.set_title('alpha values') ax.text(11.3, 0.6, 'zorder=1', va='center', color='C0') ax.text(11.3, 0, 'zorder=2\nalpha=0.8', va='center', color='C1') ax.text(11.3, -0.6, 'zorder=3', va='center', color='C0') ax.axis('off') 

alpha values

The orange rectangle is semi-transparent with alpha = 0.8. The top row of blue squares is drawn below and the bottom row of blue squares is drawn on top of the orange rectangle.

See also Zorder Demo to learn more on the drawing order.

«CN» color selection#

Matplotlib converts «CN» colors to RGBA when drawing Artists. The Styling with cycler section contains additional information about controlling colors and style properties.

import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl th = np.linspace(0, 2*np.pi, 128) def demo(sty): mpl.style.use(sty) fig, ax = plt.subplots(figsize=(3, 3)) ax.set_title('style: '.format(sty), color='C0') ax.plot(th, np.cos(th), 'C1', label='C1') ax.plot(th, np.sin(th), 'C2', label='C2') ax.legend() demo('default') demo('seaborn-v0_8') 
  • style:
  • style:

The first color ‘C0’ is the title. Each plot uses the second and third colors of each style’s rcParams[«axes.prop_cycle»] (default: cycler(‘color’, [‘#1f77b4’, ‘#ff7f0e’, ‘#2ca02c’, ‘#d62728’, ‘#9467bd’, ‘#8c564b’, ‘#e377c2’, ‘#7f7f7f’, ‘#bcbd22’, ‘#17becf’]) ). They are ‘C1’ and ‘C2’ , respectively.

Comparison between X11/CSS4 and xkcd colors#

95 out of the 148 X11/CSS4 color names also appear in the xkcd color survey. Almost all of them map to different color values in the X11/CSS4 and in the xkcd palette. Only ‘black’, ‘white’ and ‘cyan’ are identical.

For example, ‘blue’ maps to ‘#0000FF’ whereas ‘xkcd:blue’ maps to ‘#0343DF’ . Due to these name collisions, all xkcd colors have the ‘xkcd:’ prefix.

The visual below shows name collisions. Color names where color values agree are in bold.

import matplotlib.colors as mcolors import matplotlib.patches as mpatch overlap = name for name in mcolors.CSS4_COLORS if f'xkcd:name>' in mcolors.XKCD_COLORS> fig = plt.figure(figsize=[9, 5]) ax = fig.add_axes([0, 0, 1, 1]) n_groups = 3 n_rows = len(overlap) // n_groups + 1 for j, color_name in enumerate(sorted(overlap)): css4 = mcolors.CSS4_COLORS[color_name] xkcd = mcolors.XKCD_COLORS[f'xkcd:color_name>'].upper() # Pick text colour based on perceived luminance. rgba = mcolors.to_rgba_array([css4, xkcd]) luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2] css4_text_color = 'k' if luma[0] > 0.5 else 'w' xkcd_text_color = 'k' if luma[1] > 0.5 else 'w' col_shift = (j // n_rows) * 3 y_pos = j % n_rows text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None) ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4)) ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd)) ax.text(0.5 + col_shift, y_pos + .7, css4, color=css4_text_color, ha='center', **text_args) ax.text(1.5 + col_shift, y_pos + .7, xkcd, color=xkcd_text_color, ha='center', **text_args) ax.text(2 + col_shift, y_pos + .7, f' color_name>', **text_args) for g in range(n_groups): ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1) ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center') ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center') ax.set_xlim(0, 3 * n_groups) ax.set_ylim(n_rows, -1) ax.axis('off') plt.show() 

colors

Total running time of the script: ( 0 minutes 2.179 seconds)

Источник

Читайте также:  Создание HTML-таблиц
Оцените статью