colors¶
abutils provides a set of utilities for working with colors in visualizations. These utilities include
functions for creating and manipulating colormaps, generating color palettes, and converting between
different color representations. The module also includes a collection of predefined color palettes
designed for use in scientific visualizations.
All color functions are accessible through the abutils.cl module, which is the recommended way to
use these utilities in your code.
color utility |
description |
|---|---|
creates or retrieves a Matplotlib colormap |
|
creates a monochromatic color palette |
|
creates a subset of an existing colormap |
|
converts a hex color code to RGB values |
|
converts RGB values to a hex color code |
|
creates a color palette using the HLS color space |
|
creates a color palette using the HUSL color space |
|
displays the predefined color palettes |
|
dictionary of predefined color palettes |
|
a predefined palette for boolean values |
examples¶
using predefined color palettes
abutils includes several predefined color palettes that are designed for scientific visualizations:
import abutils
import matplotlib.pyplot as plt
# get a predefined palette
palette = abutils.cl.palettes['vibrant']
# use the palette in a plot
for i, color in enumerate(palette):
plt.plot([0, 1], [i, i], color=color, linewidth=10)
plt.ylim(-0.5, len(palette) - 0.5)
plt.title('Vibrant Palette')
plt.show()
# view all available palettes
abutils.cl.show_palettes()
creating custom colormaps
Create custom colormaps from a single color or modify existing colormaps:
import abutils
import numpy as np
import matplotlib.pyplot as plt
# create a colormap from a single color
cmap1 = abutils.cl.get_cmap('steelblue')
# create a colormap with a special color for zero values
cmap2 = abutils.cl.get_cmap('viridis', zero_color='lightgray')
# truncate an existing colormap
cmap3 = abutils.cl.truncate_colormap(plt.cm.plasma, minval=0.2, maxval=0.8)
# display the colormaps
fig, axes = plt.subplots(3, 1, figsize=(8, 4))
for ax, cmap, title in zip(axes, [cmap1, cmap2, cmap3],
['Monochrome', 'Zero-colored', 'Truncated']):
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
ax.imshow(gradient, aspect='auto', cmap=cmap)
ax.set_title(title)
ax.set_axis_off()
plt.tight_layout()
plt.show()
generating color palettes
Generate color palettes with different color generation methods:
import abutils
import matplotlib.pyplot as plt
# create a monochromatic palette
mono_palette = abutils.cl.monochrome_palette('darkred', n_colors=7)
# create an HLS palette
hls_palette = abutils.cl.hls(7, hue=0.6, lightness=0.6, saturation=0.8)
# create a HUSL palette
husl_palette = abutils.cl.husl(7, hue=0.1, saturation=0.9, lightness=0.65)
# display the palettes
fig, axes = plt.subplots(3, 1, figsize=(8, 3))
for ax, palette, title in zip(axes, [mono_palette, hls_palette, husl_palette],
['Monochrome', 'HLS', 'HUSL']):
for i, color in enumerate(palette):
ax.plot([i, i+0.9], [0, 0], color=color, linewidth=20)
ax.set_xlim(-0.1, len(palette))
ax.set_ylim(-0.5, 0.5)
ax.set_title(title)
ax.set_axis_off()
plt.tight_layout()
plt.show()
color conversion
Convert between RGB and hex color representations:
import abutils
# convert hex to RGB
rgb = abutils.cl.hex_to_rgb('#3498db')
print(f"Hex #3498db as RGB: {rgb}")
# convert RGB to hex
hex_code = abutils.cl.rgb_to_hex((52, 152, 219))
print(f"RGB (52, 152, 219) as hex: {hex_code}")
# convert normalized RGB (0-1) to hex
hex_code_norm = abutils.cl.rgb_to_hex((0.2, 0.6, 0.85))
print(f"Normalized RGB (0.2, 0.6, 0.85) as hex: {hex_code_norm}")
api¶
- abutils.cl.get_cmap(c: <MagicMock name='mock.colors.Colormap' id='132796525954912'> | str | ~typing.Iterable, dark: bool = False, zero_color: str | ~typing.Iterable | None = None, n: int = 256, minval: float = 0.0, maxval: float = 1.0, name: str | None = None) <MagicMock name='mock.colors.Colormap' id='132796525954912'>¶
Gets a matplotlib
Colormap.- Parameters:
c (
str,Colormaportuple) –- Can be one of several things:
matplotlib
Colormapthe name of a matplotlib
Colormap(e.g.'viridis')hex code
RGB tuple
If a single color is provided, a
Colormapwill be built from white to the provided color (or from the color to black if dark isTrue).dark (bool, default=False) – If
True, build aColormapfrom the provided color from the color to black. By default, theColormapwill be built from the provided color to white.zero_color (any Matplotlib color, default=None) – Alternate color for the zero value of the
Colormap. Produces results similar to the default colormap in 10x Genomics’ Loupe browser, in which the zero count value for GEX plots is light grey and less easily confused with near-zero counts.minval (float, default=0.0) – Truncate the lower bound of the
Colormap. Must be afloatless than 1.0, which represents the fraction of theColormapat which to truncate.maxval (float, default=1.0) – Truncate the upper bound of the
Colormap. Must be afloatgreater than zero and less than or equal to 1.0, which represents the fraction of theColormapto truncate.n (int, default=256) – Number of steps in the
Colormap.name (str, default=None) – Name of the
Colormap.
- Returns:
cmap
- Return type:
Colormap
- abutils.cl.monochrome_palette(color: str | Iterable, n_colors: int = 10, include_white: bool = False) list¶
Returns a monochromatic palette of colors, from color to white.
- Parameters:
color (str or Iterable) –
Color from which the monochromatic palette will be created. Can be one of several things:
hex code
RGB tuple
n_colors (int, default=10) – Number of colors in the palette.
include_white (bool, default=False) – Whether or not to include white in the palette. White is not included by default, meaning all colors in the palette will be a shade of color.
- Returns:
palette – A
listof RGBA ``tuple``s- Return type:
list
- abutils.cl.truncate_colormap(cmap: <MagicMock name='mock.colors.Colormap' id='132796525954912'>, minval: float = 0.0, maxval: float = 1.0, n: int = 256) <MagicMock name='mock.colors.Colormap' id='132796525954912'>¶
Truncates a colormap, such that the new colormap consists of
cmap[minval:maxval].If maxval is larger than minval, the truncated colormap will be reversed.
Args:
cmap : colormap): Colormap to be truncated.
minval (float): Lower bound. Should be a float betwee 0 and 1.
maxval (float): Upper bound. Should be a float between 0 and 1
n (int): Number of colormap steps. Default is
256.Returns:
colormap: A matplotlib colormap
- abutils.cl.hex_to_rgb(hex_string)¶
- abutils.cl.rgb_to_hex(rgb_tuple)¶
- abutils.cl.hls(n_colors, hue=0.01, lightness=0.6, saturation=0.65)¶
- abutils.cl.husl(n_colors, hue=0.01, saturation=0.9, lightness=0.65)¶
- abutils.cl.show_palettes() None¶
Displays all abutils built-in color palettes. Inspired by matplotlib’s colormaps tutorial.
- abutils.cl.palettes = dictionary of predefined color palettes¶
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s
(key, value) pairs
- dict(iterable) -> new dictionary initialized as if via:
d = {} for k, v in iterable:
d[k] = v
- dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
- abutils.cl.true_false_palette = {True: "#e41a1c", False: "#d1d1d1"}¶
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s
(key, value) pairs
- dict(iterable) -> new dictionary initialized as if via:
d = {} for k, v in iterable:
d[k] = v
- dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)