Source-linked AI summary

colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes

Achim Zeileis, Jason C. Fisher, Kurt Hornik, Ross Ihaka, Claire D. McWhite, Paul Murrell, Reto Stauffer, Claus O. Wilke

arXiv:1903.06490v1stat.COcs.GR

TL;DR

Statistical graphics need perceptually accessible color palettes, while many conventional RGB palettes vary substantially in chroma and luminance. colorspace addresses this by providing flexible HCL-based palette construction, manipulation, application, and assessment tools. Its qualitative, sequential, and diverging strategies support different data types, but user-registered palettes persist only for the current session.

  • Problem

    Conventional RGB palettes such as rainbow can have poor perceptual properties, motivating more accessible and carefully chosen colors for statistical graphics.

  • Method

    colorspace constructs, manipulates, and assesses qualitative, sequential, and diverging palettes through trajectories in HCL color space, with graphics scales and interactive tools.

  • Results

    The package provides flexible HCL palettes whose construction principles are directly accessible and that can closely approximate many palettes from RColorBrewer, rcartocolor, and viridis.

  • Takeaways & Limitations

    HCL trajectories let users adjust palettes to particular visualization needs while inspecting their perceptual properties and color-vision-deficiency suitability.

  • Takeaways & Limitations

    Palettes registered by users are stored only for the current R session and must be re-registered after restarting R.

Abstract

from arXiv · show

The R package colorspace provides a flexible toolbox for selecting individual colors or color palettes, manipulating these colors, and employing them in statistical graphics and data visualizations. In particular, the package provides a broad range of color palettes based on the HCL (Hue-Chroma-Luminance) color space. The three HCL dimensions have been shown to match those of the human visual system very well, thus facilitating intuitive selection of color palettes through trajectories in this space. Using the HCL color model general strategies for three types of palettes are implemented: (1) Qualitative for coding categorical information, i.e., where no particular ordering of categories is available. (2) Sequential for coding ordered/numeric information, i.e., going from high to low (or vice versa). (3) Diverging for coding ordered/numeric information around a central neutral value, i.e., where colors diverge from neutral to two extremes. To aid selection and application of these palettes the package also contains scales for use with ggplot2, shiny (and tcltk) apps for interactive exploration, visualizations of palette properties, accompanying manipulation utilities (like desaturation and lighten/darken), and emulation of color vision deficiencies.

1. Introduction

colorspace addresses perceptual shortcomings in conventional RGB palettes by exposing flexible HCL-based construction principles. It supports qualitative, sequential, and diverging palettes alongside tools for application, assessment, customization, and color-vision-deficiency emulation.

  • Motivation: RGB rainbow palettes can have substantial chroma and luminance variation, weakening their suitability for encoding data in statistical graphics.The paper identifies luminance variation as particularly important for perceptual quality.
  • HCL approach: HCL uses Hue, Chroma, and Luminance axes that match the human visual system well, enabling direct access to palette construction principles.colorspace derives palettes through simple trajectories in this perceptually based color space.
  • Palette types: Qualitative palettes encode unordered categories, sequential palettes encode ordered values, and diverging palettes encode values around a neutral center.The corresponding functions are qualitative_hcl(), sequential_hcl(), and diverging_hcl().
  • Palette collection: The package ships broad predefined palettes and allows existing palettes to be tweaked or new palettes registered.Its HCL choices also closely approximate many palettes from RColorBrewer, rcartocolor, and viridis using few HCL parameters.
  • Supporting tools: Scales, interactive apps, palette visualizations, manipulation utilities, and color-vision-deficiency emulation support palette selection and application.Utilities include desaturation, lighten/darken operations, and emulation for assessing colorblind viewers.

2. A quick tour

The quick tour demonstrates colorspace palette selection, use in base R and ggplot2 graphics, and visual assessment in HCL space. Examples show how qualitative palettes code groups while sequential palettes encode ordered values through luminance and chroma trajectories.

  • Choosing palettes: colorspace offers predefined HCL palettes that can be browsed with hcl_palettes() and generated by specifying a palette name and desired number of colors.The resulting color vectors can be passed directly to most base graphics functions.
  • Base graphics: Base R examples use qualitative_hcl(4, "Dark 3") for EuStockMarkets log-price time series and sequential_hcl(2, "Purples 3") for Titanic survival proportions.The sequential example uses dark purple and light gray to distinguish the two values.
  • ggplot2 usage: ggplot2 scales follow the scheme scale_<aesthetic>_<datatype>_<colorscale>(), distinguishing aesthetics, variable types, and palette classes.Available palette classes include qualitative, sequential, diverging, and divergingx.
  • ggplot2 usage: ggplot2 examples apply a qualitative scale to iris sepal-length densities by species and a sequential scale to diamonds price-by-carat points shaded by cut.The sequential example generates six colors and drops the first because its light gray is too light.
  • Assessment tools: demoplot(), hclplot(), and specplot() visualize palettes in statistical graphics, HCL coordinates, and line spectra.These functions support assessment beyond simple color swatches.
  • Qualitative assessment: The qualitative "Dark 3" palette keeps luminance almost constant while hue changes linearly, with chroma constrained by hue-dependent maximums.Lighter colors or semitransparency are preferable when shading areas such as bars or densities.
  • Sequential assessment: The sequential "Purples 3" palette keeps hue constant, increases luminance monotonically, and uses triangular chroma to distinguish middle colors.A heatmap example uses dark colors to emphasize higher volcano elevations.

3. Color spaces: S4 classes and utilities

colorspace represents and converts colors across several three-dimensional color spaces, with HCL serving as a perceptually based space for specifying colors and sRGB as a practical output representation. Its S4 classes and utilities support conversion, coordinate extraction, file I/O, and hexadecimal color coding.

  • Color-space representations: The package maps among three-dimensional color models, highlighting HCL-to-sRGB conversion for device-independent specification and standard display formats.HCL is perceptually based, whereas sRGB is commonly used for software and hardware color specifications.
  • Color-space representations: RGB is widely adopted for screen-based color generation but is device-dependent, non-uniform perceptually, and unintuitive for human color specification.sRGB addresses device dependency through gamma correction but remains unintuitive to work with directly.
  • S4 classes: All colorspace color-space classes inherit from a virtual color class and are internally represented as matrices with three columns.The columns correspond to the three dimensions of each color space.
  • Utilities: The package provides S4 conversion methods, coordinate extraction, hexadecimal conversion, hexadecimal-to-sRGB parsing, and color-file input/output utilities.The as() method converts color objects, coords() extracts coordinates, and hex() creates plotting-compatible strings.
  • Utilities: An HCL example creates pastel red, green, and blue colors with moderate chroma and luminance, then converts them to sRGB and hexadecimal codes.The resulting hex codes are "#E495A5", "#86B875", and "#7DB0DD".

4. HCL-based color palettes

colorspace constructs three palette types through trajectories in HCL space: qualitative palettes for unordered categories, sequential palettes for ordered values, and diverging palettes around a neutral center. Users can select named palettes, modify HCL parameters, and tailor palette construction to display needs.

  • Palette types: The three HCL palette functions target distinct data structures: qualitative for unordered categories, sequential for ordered values, and diverging for values around a neutral center.They are implemented as qualitative_hcl(), sequential_hcl(), and diverging_hcl().
  • Named palettes: The package includes qualitative, single-hue sequential, multi-hue sequential, and diverging named palettes, including approximations of palettes from ColorBrewer, CARTO, viridis, and scientific color maps.The named palette collection is accessible through hcl_palettes().
  • Palette specification: Named palettes can be inspected, generated, and modified either by palette name or by specifying HCL parameters directly.The first three example commands are equivalent, while increasing luminance from 70 to 80 yields lighter colors.
  • Qualitative palettes: qualitative_hcl() varies hues while keeping chroma and luminance constant so categories receive similar perceptual weight.The hue sequence is defined by starting and ending hues and normally spans the full 360-degree color wheel.
  • Palette selection: Palette choice depends on the display: lighter moderate-chroma colors are less distracting for shaded areas, whereas point and line displays often need higher chroma.On white backgrounds, moderate luminance generally works better for points and lines.
  • Sequential palettes: sequential_hcl() uses a monotonic luminance sequence, optionally adding hue variation, chroma trajectories, and power transformations.With zero chroma it produces grayscale palettes; single-hue variants can move from high chroma to gray as luminance increases.

4.3. Sequential palettes (multi-hue)

Multi-hue sequential palettes retain monotonic luminance while varying hue to improve distinction among middle colors, with chroma and power trajectories providing additional control. The package also defines diverging palettes through balanced arms that meet at a zero-chroma neutral value.

  • Multi-hue sequential palettes: Multi-hue sequential palettes combine a monotonic luminance sequence with hue intervals and monotonic or triangular chroma trajectories.This design is intended to better distinguish middle colors while retaining sequential ordering.
  • Multi-hue sequential palettes: sequential_hcl() supports combined hue, chroma, luminance, and power transformations, yielding a broad variety of adaptable sequential palettes.Many named palettes closely match established palettes from other systems.
  • Named palettes: Named multi-hue palettes include colorspace-developed palettes and close matches to matplotlib, CARTO, ColorBrewer, and Crameri scientific color maps.Some Crameri-matched palettes are intended for black or dark backgrounds.
  • Diverging palettes: Diverging palettes use two hues in balanced left and right arms, with triangular luminance trajectories and zero chroma at the neutral center.Each arm uses one hue, and chroma and luminance are balanced between arms.
  • Palette assessment: Strong luminance contrast is important when many colors are used, whereas fewer colors can tolerate smaller luminance contrasts.The same consideration applies to sequential and diverging palettes.
  • Construction details: Chroma trajectories may be constant, linear, or triangular, and power parameters below or above 1 make chroma change more slowly or quickly.Figure 13 illustrates these trajectories with concrete constant, linear, and triangular parameter settings.
  • Custom palettes: Custom palettes can be registered for later reuse, but registration persists only for the current R session unless startup code recreates it.Registering an existing name overwrites the old palette, and the registered color count can later be modified.

4.7. Flexible diverging palettes

colorspace provides flexible diverging HCL palettes by combining sequential palette arms, allowing unbalanced trajectories and non-gray neutral colors. It also approximates palettes from other R packages while offering tools for reconstruction and base-R compatibility.

  • Flexible diverging palettes: divergingx_hcl() constructs flexible diverging palettes by calling sequential_hcl() twice, without requiring balanced arms or a gray neutral.The two arms can use separate hue, chroma, and luminance parameters.
  • Prespecified palettes: Named palettes from CARTO, ColorBrewer.org, wesanderson, and viridis are closely matched by colorspace palettes.The named families include ArmyRose–Tropic, PuOr–Spectral, Zissou 1, and Cividis.
  • Prespecified palettes: Cividis combines blue and yellow arms with a low-chroma center but is better classified as sequential because luminance changes monotonically from dark to light.Its unusual hue, chroma, and luminance trajectories require special treatment.
  • Approximating external palettes: The HCL-based approximations of four external palettes are very close to the originals for most colors, despite not being identical.The comparison includes YlGnBu, Viridis, ag_Sunset, and Plasma; boundary constraints can create kinks in chroma trajectories.
  • Approximating external palettes: Viridis and Plasma maintain relatively high chroma, which is less suitable for sequential palettes on light backgrounds but works better on dark backgrounds.Their hue and luminance trajectories resemble comparator palettes, while their chroma trajectories differ.
  • Base-R interfaces: colorspace supplies convenience interfaces for HCL replacements of base-R palettes, including rainbow_hcl(), heat_hcl(), and terrain_hcl().The package also provides diverging_hsv() for palettes generated in HSV space.

5. Palette visualization and assessment

colorspace visualizes palette properties through swatches, HCL spectra, and projections in HCL space. These tools expose trajectory structure and help assess balance, perceptual behavior, and suitability across palette types.

  • Visualization toolbox: colorspace provides swatchplot(), specplot(), hclplot(), and demoplot() for visualizing palettes and their properties.The functions cover swatches, HCL/RGB spectra, HCL-space projections, and simplified statistical graphics.
  • Palette construction: Sequential palette variants retain monotonically increasing luminance while changing hue and chroma trajectories to emphasize extremes or middle colors.Single-hue palettes emphasize extremes; triangular chroma improves middle-color distinction; multi-hue designs increase color contrast.
  • HCL and RGB spectra: specplot() transforms palettes into HCL coordinates and displays hue, chroma, and luminance trajectories, optionally alongside RGB trajectories.Hue smoothing and circular shifting reduce instability for low-chroma colors and hue wraparound.
  • HCL and RGB spectra: A balanced Green-Brown palette combines two sequential arms with balanced chroma and luminance paths around a light-gray neutral.Its RGB spectrum also illustrates why balanced palettes are difficult to design directly in RGB space.
  • HCL and RGB spectra: The RGB rainbow palette produces substantial chroma and luminance variation, making it unsuitable for encoding underlying data in statistical graphics.Its RGB trajectory is simple, but its perceptual dimensions are not.
  • Trajectories in HCL space: hclplot() projects palette coordinates into a two-dimensional HCL heatmap and highlights the palette trajectory.It collapses luminance for qualitative palettes and hue for sequential or diverging palettes, using a linear model when the collapsed coordinate varies.
  • Trajectories in HCL space: HCL-space geometry constrains achievable chroma differently across hues, requiring chroma reduction for some dark, low-luminance colors.For example, H = 245 cannot sustain high chroma as far into dark colors as H = 260.

6. Color vision deficiency emulation

The package emulates several color vision deficiencies and uses these transformations to assess palette suitability. A Maunga Whau heatmap contrasts the misleading RGB rainbow with an HCL-based blue-yellow sequential palette.

  • The package emulates deuteranopia, protanopia, and tritanopia using physiologically based color-vision-deficiency models.These correspond to defective green, red, and blue cone cells, respectively.
  • simulate_cvd() transforms valid R colors with color-vision-deficiency transformation matrices, while deutan(), protan(), and tritan() provide convenience interfaces.
  • Figure 28 compares an RGB rainbow heatmap with an HCL-based blue-yellow palette under multiple simulated color deficiencies.The heatmap uses the Maunga Whau volcano data, with original palettes in the first row and simulated deficiencies in subsequent rows.
  • A grayscale perspective visualization provides an additional intuitive view of the Maunga Whau terrain for interpreting the heatmap.
  • The RGB rainbow often gives misleading terrain impressions because its luminance is not monotonic, whereas the HCL-based blue-yellow palette works reasonably well across settings.

7. Apps for choosing colors and palettes interactively

colorspace provides graphical interfaces for constructing palettes, selecting individual colors, and examining color-vision deficiencies. The apps support local and online use, with interactive controls for palette parameters and assessment.

  • The package provides shiny apps for palette construction, color picking, and color-vision-deficiency emulation, available locally and online.The online interfaces are provided at hclwizard.org.
  • The palette constructor is available through Tcl/Tk or shiny, with Tcl/Tk faster locally and shiny offering more features and online access.
  • The palette constructor interactively modifies starting and ending hue, chroma, luminance, and power transformations controlling palette trajectories.
  • The color picker displays HCL space as hue-chroma or luminance-chroma planes and accepts coordinate clicks, sliders, or RGB hex codes.
  • The color picker can repeat selections to construct a palette for subsequent use in R visualizations.
  • The CVD emulator checks uploaded JPG or PNG raster images for supported deficiencies at a selected severity, defaulting to 100%.

8. Color manipulation and utilities

The package includes utilities for desaturation, lightening and darkening, chroma limits, and additive color mixing. These operations use HCL-based transformations to create, assess, and adapt palettes while exposing practical trade-offs.

  • colorspace provides utilities for desaturation, lightening, darkening, maximum-chroma computation, and additive color mixing.
  • desaturate() sets HCL chroma to zero while preserving luminance, producing a gray with the corresponding perceptual brightness.
  • The RGB rainbow produces strongly different grayscale levels, whereas rainbow_hcl() is designed to balance luminance across hues.
  • Lightening or darkening in HCL adjusts luminance while preserving hue and chroma, but darkening light, low-chroma colors can produce overly gray results.
  • HCL-based transformation typically performs best for lightening, while a combined strategy is the default for darkening; alternative strategies may help when defaults misbehave.
  • max_chroma() approximately computes the greatest feasible chroma for a specified hue and luminance before conversion to RGB hex colors.Maximum chroma varies substantially with hue and also across luminance values for a fixed hue.
  • mixcolor() combines colors by computing their convex combination, such as mixing saturated red and green into a medium brownish yellow.

9. Summary and discussion

colorspace is presented as a flexible toolbox for selecting, manipulating, and visualizing colors and palettes. Its HCL-based palettes emphasize adaptable construction, while complementary tools and implementations extend its practical use.

  • The package supports selecting individual colors and palettes, manipulating colors, and employing them in visualizations.
  • Qualitative, sequential, and diverging palettes are derived from relatively simple trajectories in HCL space.
  • Compared with several other modern palette packages, colorspace emphasizes flexibility to adjust palettes to particular data-visualization needs.
  • Polychrome complements colorspace by targeting qualitative palettes with many categories, beyond the roughly 6–8 clearly distinguishable colors described for colorspace qualitative palettes.
  • A Python 2/Python 3 reimplementation is available in beta, while the manuscript focuses on the more mature R implementation.

Computational details

The paper’s results were obtained in R 3.5.2 using specified versions of colorspace and related visualization packages. R and all used packages are available through CRAN.

  • R 3.5.2 was used to obtain the paper’s results.
  • The computational environment included colorspace 1.4.1, ggplot2 3.1.0, RColorBrewer 1.1.2, rcartocolor 0.0.22, viridis 0.5.1, and scico 1.1.0.
  • R and all packages used are available from the Comprehensive R Archive Network (CRAN).
Loading 1903.06490v1…