Compute (and visualize) the contrast ratio of pairs of colors, as defined by the World Wide Web Consortium (W3C). Requires matplotlib to be installed.
The W3C Content Accessibility Guidelines (WCAG) recommend a contrast ratio of at least 4.5 for the color of regular text on the background color, and a ratio of at least 3 for large text. See https://www.w3.org/TR/WCAG21/#contrast-minimum.
The contrast ratio is defined in https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio as (L1 + 0.05) / (L2 + 0.05) where L1 and L2 are the relative luminances (see https://www.w3.org/TR/WCAG21/#dfn-relative-luminance) of the lighter and darker colors, respectively. The relative luminances are weighted sums of scaled sRGB coordinates: 0.2126 * R + 0.7152 * G + 0.0722 * B where each of R, G, and B is defined as RGB / 12.92 if RGB <= 0.03928 else (RGB + 0.055)/1.055)^2.4 based on the RGB coordinates between 0 and 1.
Single hex color (str), a list of hex colors (list), a color object , or palette.
bgstr
background color against which the contrast will be calculated. Defaults to white ("#FFFFFF").
plotbool
logical indicating whether the contrast ratios should also be visualized by simple color swatches.
axNone or matplotlib.axes.Axes
If None, a new matplotlib figure will be created. If ax inherits from matplotlib.axes.Axes this object will be used to create the demoplot. Handy to create multiple subplots. Forwarded to different plot types.
fontsizefloat, str
size of text, forwarded to matplotlib.pyplot.text. Defaults to "xx-large".
fontweightstr
weight of text, forwarded to matplotlib.pyplot.text. Defaults to "heavy".
hastr
horizontal alignment, forwarded to matplotlib.pyplot.text. Defaults to "center".
vastr
vertical alignment, forwarded to matplotlib.pyplot.text. Defaults to "center".
**kwargs
Allows to specify figsize forwarded to maptlotlib.pyplot.figure, only used if ax is None.
Return
A numeric vector with the contrast ratios is returned (invisibly, if plot is True).
Examples
# check contrast ratio of default palette on white backgroundfrom colorspace import rainbow, contrast_ratiocolors = rainbow().colors(7)contrast_ratio(colors, "#FFFFFF") # Against whitecontrast_ratio(colors, "#000000") # Against black