Skip to content

ragraph.colors

RaGraph colors and palettes

This module contains several convenient methods to obtain color palettes as lists of hex-coded colors. The defaults for categorical and continuous data are get_categorical and get_continuous, respectively.

Additional methods are included, most of which are based on the cubehelix palette with certain preset options. get_hue is a great way to get a sequential color palette for any hue where the hue value corresponds to anything between red (1.0), green (2.0) or blue (3.0).

In our plots, these colors are not interpolated. This opens up an easy way to visualize your colors in a discrete fashion, since you merely need to supply a list with less colors (e.g. the desired number of discrete steps).

get_blue

get_blue(n_colors: int = 256, **kwargs) -> List[str]

Get a blue sequential color palette.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

256

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_blue(n_colors: int = 256, **kwargs) -> List[str]:
    """Get a blue sequential color palette.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    opts: Dict[str, Any] = dict(hue=2.85, n_colors=n_colors)
    opts.update(**kwargs)
    return get_hue(**opts)

get_categorical

get_categorical(n_colors: int = 10, **kwargs) -> List[str]

Get a color palette suitable for categorical data.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

10

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_categorical(n_colors: int = 10, **kwargs) -> List[str]:
    """Get a color palette suitable for categorical data.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    n_colors = max(n_colors, 1)
    base_light = 0.6
    if n_colors <= 10:
        dark = base_light
        light = base_light
    else:
        excess = n_colors - 10
        dark = max(0.3, base_light - excess * 0.05)
        light = min(0.8, base_light + excess * 0.05)
    opts: Dict[str, Any] = dict(
        n_colors=n_colors,
        start=2.8,
        rotations=(n_colors - 1) / n_colors,
        dark=light,  # Get the darker colors first.
        light=dark,
        gamma=1.0,
        saturation=1.8,
        categorical=True,
    )
    opts.update(kwargs)
    return cubehelix_palette(**opts)

get_colormaps

1
2
3
4
5
6
get_colormaps(
    n_colors: int = 1,
    kind: str = "categorical",
    amount: int = 1,
    flip: bool = False,
) -> List[List[str]]

Get multiple colormaps of a certain kind.

Parameters:

Name Type Description Default
n_colors int

Number of colors per colormap to generate.

1
kind str

Kind of colormap. One of 'categorical', 'sequential', or 'diverging'.

'categorical'
amount int

Number of colormaps to generate.

1
flip bool

Whether to reverse the generated colormaps.

False
Source code in ragraph/colors/__init__.py
def get_colormaps(
    n_colors: int = 1,
    kind: str = "categorical",
    amount: int = 1,
    flip: bool = False,
) -> List[List[str]]:
    """Get multiple colormaps of a certain kind.

    Arguments:
        n_colors: Number of colors per colormap to generate.
        kind: Kind of colormap. One of 'categorical', 'sequential', or 'diverging'.
        amount: Number of colormaps to generate.
        flip: Whether to reverse the generated colormaps.
    """
    if kind == "categorical":
        return [get_categorical(n_colors=n_colors)]
    elif kind == "sequential":
        if amount == 1:
            colormaps = [get_continuous(n_colors=n_colors)]
        else:
            colormaps = [
                get_hue(n_colors=n_colors, hue=2.85 + 3 * i / amount) for i in range(amount)
            ]
    elif kind == "diverging":
        colormaps = [
            get_diverging_hues(
                n_colors=n_colors,
                lower_hue=0.95 - 1.0 * i / amount,
                upper_hue=2.85 - 2 * i / amount,
            )
            for i in range(amount)
        ]
    else:
        allowed = ["categorical", "sequential", "diverging"]
        raise ValueError(f"Unknown colormap kind. Pick one of '{allowed}'.")

    if flip:
        return [colormap[::-1] for colormap in colormaps]
    else:
        return colormaps

get_continuous

get_continuous(n_colors: int = 256, **kwargs) -> List[str]

Get a default color palette suitable for continuous valued data.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

256

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_continuous(n_colors: int = 256, **kwargs) -> List[str]:
    """Get a default color palette suitable for continuous valued data.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    n_colors = max(n_colors, 1)
    opts: Dict[str, Any] = dict(
        n_colors=n_colors,
        start=2.25,
        end=3.45,
        dark=0.2,
        light=0.85,
        gamma=1.0,
        saturation=1.2,
        categorical=False,
    )
    opts.update(kwargs)
    return cubehelix_palette(**opts)

get_cyan

get_cyan(n_colors: int = 256, **kwargs) -> List[str]

Get a cyan sequential color palette.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

256

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_cyan(n_colors: int = 256, **kwargs) -> List[str]:
    """Get a cyan sequential color palette.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    opts: Dict[str, Any] = dict(hue=2.45, n_colors=n_colors)
    opts.update(**kwargs)
    return get_hue(**opts)

get_diverging_hues

1
2
3
4
5
6
7
get_diverging_hues(
    n_colors: int = 257,
    lower_hue: float = 0.95,
    upper_hue: float = 2.85,
    midpoint: float = 0.5,
    **kwargs
) -> List[str]

Get a diverging color palette between two hues.

Parameters:

Name Type Description Default
n_colors int

Number of colors (will always return an uneven number of colors).

257
lower_hue float

Lower bound hue value.

0.95
upper_hue float

Upper bound hue value.

2.85
midpoint float

Fraction between [0.0, 1.0] where to put the midpoint.

0.5

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_diverging_hues(
    n_colors: int = 257,
    lower_hue: float = 0.95,
    upper_hue: float = 2.85,
    midpoint: float = 0.5,
    **kwargs,
) -> List[str]:
    """Get a diverging color palette between two hues.

    Arguments:
        n_colors: Number of colors (will always return an uneven number of colors).
        lower_hue: Lower bound hue value.
        upper_hue: Upper bound hue value.
        midpoint: Fraction between [0.0, 1.0] where to put the midpoint.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    if n_colors <= 1:
        return ["#ffffff"]

    midindex = round(midpoint * (n_colors - 1))
    lower = get_hue(hue=lower_hue, n_colors=midindex + 1, **kwargs)
    upper = get_hue(hue=upper_hue, n_colors=n_colors - midindex, **kwargs)
    return lower[::-1] + upper[1:]

get_diverging_orangecyan

1
2
3
get_diverging_orangecyan(
    n_colors: int = 257, **kwargs
) -> List[str]

Get a orange-white-cyan diverging color palette.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

257

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_diverging_orangecyan(n_colors: int = 257, **kwargs) -> List[str]:
    """Get a orange-white-cyan diverging color palette.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    opts: Dict[str, Any] = dict(lower_hue=1.2, upper_hue=2.45, n_colors=n_colors)
    opts.update(kwargs)
    return get_diverging_hues(**opts)

get_diverging_purplegreen

1
2
3
get_diverging_purplegreen(
    n_colors: int = 257, **kwargs
) -> List[str]

Get a purple-white-green diverging color palette.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

257

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_diverging_purplegreen(n_colors: int = 257, **kwargs) -> List[str]:
    """Get a purple-white-green diverging color palette.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    opts: Dict[str, Any] = dict(lower_hue=0.15, upper_hue=1.8, n_colors=n_colors)
    opts.update(kwargs)
    return get_diverging_hues(**opts)

get_diverging_redblue

1
2
3
get_diverging_redblue(
    n_colors: int = 257, **kwargs
) -> List[str]

Get a red-white-blue diverging color palette.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

257

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_diverging_redblue(n_colors: int = 257, **kwargs) -> List[str]:
    """Get a red-white-blue diverging color palette.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    opts: Dict[str, Any] = dict(lower_hue=0.95, upper_hue=2.85, n_colors=n_colors)
    opts.update(kwargs)
    return get_diverging_hues(**opts)

get_green

get_green(n_colors: int = 256, **kwargs) -> List[str]

Get a green sequential color palette.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

256

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_green(n_colors: int = 256, **kwargs) -> List[str]:
    """Get a green sequential color palette.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    opts: Dict[str, Any] = dict(hue=1.8, n_colors=n_colors)
    opts.update(**kwargs)
    return get_hue(**opts)

get_hue

1
2
3
get_hue(
    n_colors: int = 256, hue: float = 1.0, **kwargs
) -> List[str]

Get a sequential color palette with the given hue.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

256
hue float

Hue for this sequential color palette.

1.0

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_hue(n_colors: int = 256, hue: float = 1.0, **kwargs) -> List[str]:
    """Get a sequential color palette with the given hue.

    Arguments:
        n_colors: Number of colors to generate.
        hue: Hue for this sequential color palette.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    n_colors = max(n_colors, 1)
    opts: Dict[str, Any] = dict(
        n_colors=n_colors,
        start=hue,
        end=hue,
        dark=0.25,
        light=1.0,
        gamma=1.0,
        saturation=1.8,
        categorical=False,
    )
    opts.update(**kwargs)
    return cubehelix_palette(**opts)

get_orange

get_orange(n_colors: int = 256, **kwargs) -> List[str]

Get an orange sequential color palette.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

256

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_orange(n_colors: int = 256, **kwargs) -> List[str]:
    """Get an orange sequential color palette.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    opts: Dict[str, Any] = dict(hue=1.2, n_colors=n_colors)
    opts.update(**kwargs)
    return get_hue(**opts)

get_purple

get_purple(n_colors: int = 256, **kwargs) -> List[str]

Get a purple sequential color palette.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

256

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_purple(n_colors: int = 256, **kwargs) -> List[str]:
    """Get a purple sequential color palette.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    opts: Dict[str, Any] = dict(hue=0.15, n_colors=n_colors)
    opts.update(**kwargs)
    return get_hue(**opts)

get_red

get_red(n_colors: int = 256, **kwargs) -> List[str]

Get a red sequential color palette.

Parameters:

Name Type Description Default
n_colors int

Number of colors to generate.

256

Returns:

Type Description
List[str]

A list of colors as hex codes.

Note

Additional keyword arguments are passed on to cubehelix_palette.

Source code in ragraph/colors/__init__.py
def get_red(n_colors: int = 256, **kwargs) -> List[str]:
    """Get a red sequential color palette.

    Arguments:
        n_colors: Number of colors to generate.

    Returns:
        A list of colors as hex codes.

    Note:
        Additional keyword arguments are passed on to
        [`cubehelix_palette`][ragraph.colors.cubehelix.cubehelix_palette].
    """
    opts: Dict[str, Any] = dict(hue=0.95, n_colors=n_colors)
    opts.update(**kwargs)
    return get_hue(**opts)

cubehelix

Cubehelix color palette

Reference

Green, D. A. (2011). A colour scheme for the display of astronomical intensity images. Bull. Astr. Soc. India. Retrieved from http://www.astro.caltech.edu/.

cubehelix_palette

cubehelix_palette(
    n_colors: int,
    start: float = 2.25,
    end: float = 3.45,
    dark: float = 0.2,
    light: float = 0.85,
    gamma: float = 1.0,
    saturation: float = 1.2,
    rotations: Optional[float] = None,
    categorical: bool = False,
) -> List[str]

Calculate a cubehelix color palette as a list of hex codes.

Parameters:

Name Type Description Default
n_colors int

Number of RGB colour pairs to generate.

required
start float

Starting color (Red: 1.0, Green: 2.0, Blue: 3.0).

2.25
end float

Final color (Red: 1.0, Green: 2.0, Blue: 3.0).

3.45
dark float

Lightness of the darkest value [0.0 - 1.0].

0.2
light float

Lightness of the lightest value [0.0 - 1.0].

0.85
gamma float

Exponential factor applied to lightness to emphasize low intensity values (< 1.0) or high intensity values (> 1.0).

1.0
rotations Optional[float]

Number of RGB rotations (1.0 means a full RGB rotation). Overrides end. Otherwise calculated as (end - start) / 3.

None
categorical bool

Whether to shuffle the rotational space optimally for categorical color palettes. Similar colors are positioned as far apart as possible.

False

Returns:

Type Description
List[str]

Color palette as a list of hex codes.

Reference

Green, D. A. (2011). A colour scheme for the display of astronomical intensity images. Bull. Astr. Soc. India. Retrieved from http://www.astro.caltech.edu/

Source code in ragraph/colors/cubehelix.py
def cubehelix_palette(
    n_colors: int,
    start: float = 2.25,
    end: float = 3.45,
    dark: float = 0.2,
    light: float = 0.85,
    gamma: float = 1.0,
    saturation: float = 1.2,
    rotations: Optional[float] = None,
    categorical: bool = False,
) -> List[str]:
    """Calculate a cubehelix color palette as a list of hex codes.

    Arguments:
        n_colors: Number of RGB colour pairs to generate.
        start: Starting color (Red: 1.0, Green: 2.0, Blue: 3.0).
        end: Final color (Red: 1.0, Green: 2.0, Blue: 3.0).
        dark: Lightness of the darkest value [0.0 - 1.0].
        light: Lightness of the lightest value [0.0 - 1.0].
        gamma: Exponential factor applied to lightness to emphasize low intensity values (< 1.0) or
            high intensity values (> 1.0).
        rotations: Number of RGB rotations (1.0 means a full RGB rotation). Overrides `end`.
            Otherwise calculated as `(end - start) / 3`.
        categorical: Whether to shuffle the rotational space optimally for categorical color
            palettes. Similar colors are positioned as far apart as possible.

    Returns:
        Color palette as a list of hex codes.

    Reference:
        Green, D. A. (2011). A colour scheme for the display of astronomical intensity images. Bull.
        Astr. Soc. India. Retrieved from http://www.astro.caltech.edu/
    """
    if HAVE_NUMPY:
        method = _cubehelix_numpy
    else:
        method = _cubehelix_pure_python

    n_colors = max(n_colors, 1)

    rgb1s = method(
        n_colors,
        start=start,
        end=end,
        dark=dark,
        light=light,
        gamma=gamma,
        saturation=saturation,
        rotations=rotations,
        categorical=categorical,
    )

    hexes = [utils.rgb_to_hex(*utils.rgb1_to_rgb(*c)) for c in rgb1s]

    return hexes

utils

Color utilities

hex_to_rgb

hex_to_rgb(h: str) -> Tuple[int, int, int]

Convert hex code to RGB tuple.

Source code in ragraph/colors/utils.py
def hex_to_rgb(h: str) -> Tuple[int, int, int]:
    """Convert hex code to RGB tuple."""
    h = h.lstrip("#")
    n = len(h)
    rgb = tuple(int(h[i : i + n // 3], 16) for i in range(0, n, n // 3))
    return rgb[0], rgb[1], rgb[2]

rgb1_to_rgb

1
2
3
rgb1_to_rgb(
    r: float, g: float, b: float
) -> Tuple[int, int, int]

Convert [0.0-1.0] scaled RGB to [0-255].

Source code in ragraph/colors/utils.py
6
7
8
def rgb1_to_rgb(r: float, g: float, b: float) -> Tuple[int, int, int]:
    """Convert [0.0-1.0] scaled RGB to [0-255]."""
    return round(r * 255), round(g * 255), round(b * 255)

rgb_to_hex

rgb_to_hex(r: int, g: int, b: int) -> str

Convert RGB color to hex code.

Source code in ragraph/colors/utils.py
def rgb_to_hex(r: int, g: int, b: int) -> str:
    """Convert RGB color to hex code."""
    return "#{0:02x}{1:02x}{2:02x}".format(r, g, b)

rgb_to_rgb1

1
2
3
rgb_to_rgb1(
    r: int, g: int, b: int
) -> Tuple[float, float, float]

Convert [0-255] scaled RGB to [0.0-1.0].

Source code in ragraph/colors/utils.py
def rgb_to_rgb1(r: int, g: int, b: int) -> Tuple[float, float, float]:
    """Convert [0-255] scaled RGB to [0.0-1.0]."""
    return r / 255, g / 255, b / 255