colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes¶
Overview The colorspace package provides a broad toolbox for selecting individual colors or color palettes, manipulating these colors, and employing them in various kinds of visualizations.
At the core of the package there are various utilities for computing with color
spaces (as the name of the package conveys). Thus, the package helps to map
various three-dimensional representations of color to each other. A
particularly important mapping is the one from the perceptually-based and
device-independent color model HCL (Hue-Chroma-Luminance) to standard
Red-Green-Blue (sRGB) which is the basis for color specifications in many
systems based on the corresponding hex codes (e.g., in HTML but also in R). For
completeness further standard color models are included as well in the package:
polarLUV
(= HCL
),
CIELUV
,
polarLAB
,
CIELAB
,
CIEXYZ
,
RGB
,
sRGB
,
HLS
,
HSV
.
The HCL space (= polar coordinates in CIELUV) is particularly useful for specifying individual colors and color palettes as its three axes match those of the human visual system very well: Hue (= type of color, dominant wavelength), chroma (= colorfulness), luminance (= brightness).
In [1]: from colorspace import palette, sequential_hcl, swatchplot
In [2]: H = palette(sequential_hcl(h = [0, 300], c = 60, l = 65).colors(5), "Hue")
In [3]: C = palette(sequential_hcl(h = 0, c = [0, 100], l = 65).colors(5), "Chroma")
In [4]: L = palette(sequential_hcl(h = 0, c = 0, l = [90, 25]).colors(5), "Luminance")
In [5]: fig = swatchplot([H, C, L], figsize = (3, 1.5))
The colorspace package provides three types of palettes based on the HCL model:
Qualitative: Designed for coding categorical information, i.e., where no particular ordering of categories is available and every color should receive the same perceptual weight. Class:
qualitative_hcl
.Sequential: Designed for coding ordered/numeric information, i.e., where colors go from high to low (or vice versa). Class:
sequential_hcl
.Diverging: Designed for coding ordered/numeric information around a central neutral value, i.e., where colors diverge from neutral to two extremes. Class:
diverging_hcl
.
To aid choice and application of these palettes there are: scales for use with matplotlib and an app for interactive exploration; visualizations of palette properties; accompanying manipulation utilities (like desaturation, lighten/darken, and emulation of color vision deficiencies).
Todo
Darken and lighten not yet implemented.
More detailed overviews and examples are provided in the articles:
- API Reference
- Package Installation
- Color Spaces: Classes and Utilities
- HCL-Based Color Palettes
- Main Classes and Methods
- Palette Visualization and Assessment
- Apps for Choosing Colors and Palettes Interactively
- Color Vision Deficiency Emulation
- Color Manipulation and Utilities
- Approximating Palettes from Other Packages
- Somewhere over the Rainbow
Installation¶
At the moment the package is available via [github](github) github.com/retostauffer/python-colorspace. Note that numpy needs to be installed to be able to use the package. A PyPI release is planned in the future.
Requirements:
Python 2.7+ or Python 3+
numpy
Install via pip
The package can be installed via pip using the following command:
pip install https://github.com/retostauffer/python-colorspace
Clone git Repository
Alternatively, clone the git repository and install the package:
git clone https://github.com/retostauffer/python-colorspace.git
cd python-colorspace && python setup.py install
Todo
Update once released on PyPI.
Choosing HCL-based color palettes¶
The colorspace package ships with a wide range of predefined color palettes,
specified through suitable trajectories in the HCL (hue-chroma-luminance) color
space. A quick overview can be gained easily with the
hcl_palettes
function:
In [6]: from colorspace import hcl_palettes
In [7]: hcl_palettes(plot = True, figsize = (15, 10))
Out[7]: False
A suitable palette object can be easily computed by specifying the desired palette name (see the plot above), e.g.,
In [8]: from colorspace import qualitative_hcl
In [9]: pal = qualitative_hcl("Dark 3")
In [10]: pal(4) # Draw list of 4 colors across the palette
Out[10]: ['#E16A86', '#50A315', '#009ADE', '#E16A86']
The functions sequential_hcl
and
diverging_hcl
work analogously.
Additionally, their hue/chroma/luminance parameters can be modified, thus
allowing for easy customization of each palette. Moreover, the
choose_palette
app provides a convenient user interfaces to perform
palette customization interactively.
Todo
Adjust text when adding divergingx_hcl() (_Finally, even more flexible diverging HCL palettes are provided by divergingx_hcl()
Use with matplotlib graphics¶
All color palettes come with a cmap() method to generate objects of class LinearSegmentedColormap as used by the matplotlib and can thus usually be passed directly to most matplotlib plotting functions, typically trough the cmap argument. Here, a pcolormesh() example is shown using the diverging HCL color palette “Blue-Red 3”.
In [11]: import matplotlib.pyplot as plt
In [12]: import numpy as np
In [13]: from colorspace import diverging_hcl
In [14]: pal = diverging_hcl("Blue-Red 3")
In [15]: np.random.seed(19680801)
In [16]: Z = np.random.rand(6, 10)
In [17]: x = np.arange(-0.5, 10, 1) # len = 11
In [18]: y = np.arange(4.5, 11, 1) # len = 7
In [19]: fig, ax = plt.subplots()
In [20]: dead_end = ax.pcolormesh(x, y, Z, cmap = pal.cmap())
In [21]: plt.show()
As another example for a sequential palette, we demonstrate how to create a line plot using rainbowplot() provided by the statsmodels package. The Purples 3 palette is used which is quite similar to the ColorBrewer2.org palette Purples. Here, only two colors are employed, yielding a dark purple and a light gray.
In [22]: import numpy as np
In [23]: import matplotlib.pyplot as plt
In [24]: import statsmodels.api as sm
In [25]: data = sm.datasets.elnino.load()
In [26]: from colorspace import sequential_hcl
In [27]: pal = sequential_hcl("Purples 3")
In [28]: fig = plt.figure()
In [29]: ax = fig.add_subplot(111)
In [30]: res = sm.graphics.rainbowplot(data.raw_data.iloc[:, 1:], ax = ax, cmap = pal.cmap())
In [31]: dead_end = ax.set_xlabel("Month of the year")
In [32]: dead_end = ax.set_ylabel("Sea surface temperature (C)")
In [33]: dead_end = ax.set_xticks(np.arange(13, step=3) - 1)
In [34]: dead_end = ax.set_xticklabels(["", "Mar", "Jun", "Sep", "Dec"])
In [35]: dead_end = ax.set_xlim([-0.2, 11.2])
In [36]: plt.show()
Palette visualization and assessment¶
The colorspace package also provides a number of functions that aid
visualization and assessment of its palettes. The demos module
contains a series of generic/basic plot types as used by the
interactive interface (choose_palette
) which
can also be used in-line to test color palettes.
In addition specplot
allows to visualize and
graphically assess the spectrum of a series of colors in the RGB and HCL spectrum.
Visualization of the RGB and HCL spectrum given a set of hex colors. |
|
Plotting the barplot example. |
|
Plotting pie chart example. |
|
Plotting spine plot example. |
|
Plotting heatmap example. |
|
Plotting matrix example. |
|
Plotting lineplot example. |
|
Plotting example. |
In [37]: from colorspace import diverging_hcl, specplot
In [38]: pal = diverging_hcl("Purple-Green")
In [39]: fig = specplot(pal(100), hcl = True, palette = True, rgb = True)
In [40]: from colorspace import diverging_hcl, demos
In [41]: pal = diverging_hcl("Purple-Green")
In [42]: fig = demos.Bar(pal(10))