spac.utils.color_mapping(labels, color_map='viridis', opacity=1.0, rgba_mode=True, return_dict=False)[source]

Map a list of labels to colors using a Matplotlib colormap and opacity.

This function assigns a unique color to each label in the provided list using a specified colormap from Matplotlib. The generated colors can be returned in either rgba or rgb format, suitable for visualization in libraries like Plotly.

The function supports both continuous and discrete colormaps: - Continuous colormaps interpolate smoothly between colors across a range. - Discrete colormaps have a fixed number of distinct colors, and labels are

distributed evenly across these colors.

Opacity can be set with a value between 0 (fully transparent) and 1 (fully opaque). The resulting colors are CSS-compatible strings.

Parameters:
  • labels (list) – A list of unique labels to map to colors. The number of labels determines how the colormap is sampled.

  • color_map (str, optional) – The colormap name (e.g., ‘viridis’, ‘plasma’, ‘inferno’). It must be a valid Matplotlib colormap. Default is ‘viridis’.

  • opacity (float, optional) – Opacity (alpha channel) for colors, between 0 (transparent) and 1 (opaque). Default is 1.0.

  • rgba_mode (bool, optional) – If True, returns colors in rgba format (e.g., rgba(255, 0, 0, 0.5)). If False, returns rgb format (e.g., rgb(255, 0, 0)). Default is True.

  • return_dict (bool, optional) – If True, returns a dictionary where keys are labels, and values are the corresponding colors. Default is False.

Returns:

label_colors – If return_dict is False, returns a list of color strings, one for each label. If return_dict is True, returns a dictionary with label keys and color values. The format of the colors depends on the rgba_mode parameter.

Return type:

list[str] or dict

Raises:

ValueError

  • If opacity is not in the range [0, 1]. - If color_map is not a valid Matplotlib colormap name.

Examples

Assign colors to labels with default settings:

>>> labels = ['A', 'B', 'C']
>>> color_mapping(labels)
['rgba(68, 1, 84, 1.0)', 'rgba(58, 82, 139, 1.0)',
 'rgba(33, 145, 140, 1.0)']

Use a different colormap with reduced opacity:

>>> color_mapping(labels, color_map='plasma', opacity=0.5)
['rgba(13, 8, 135, 0.5)', 'rgba(126, 3, 167, 0.5)',
 'rgba(240, 249, 33, 0.5)']

Generate colors in rgb format:

>>> color_mapping(labels, rgba_mode=False)
['rgb(68, 1, 84)', 'rgb(58, 82, 139)', 'rgb(33, 145, 140)']

Return a dictionary of labels and colors:

>>> color_mapping(labels, return_dict=True)
{'A': 'rgba(68, 1, 84, 1.0)', 'B': 'rgba(58, 82, 139, 1.0)',
 'C': 'rgba(33, 145, 140, 1.0)'}

Notes