DataSetFilters.color_labels

DataSetFilters.color_labels#

DataSetFilters.color_labels(
colors: str | ColorLike | Sequence[ColorLike] | dict[float | str, ColorLike] | ColormapOptions = 'glasbey_category10',
*,
coloring_mode: Literal['index', 'cycle'] | None = None,
color_type: Literal['int_rgb', 'float_rgb', 'int_rgba', 'float_rgba'] = 'int_rgb',
negative_indexing: bool = False,
scalars: str | None = None,
preference: PointLiteral | CellLiteral = 'cell',
output_scalars: str | None = None,
return_dict: bool = False,
inplace: bool = False,
) → _DataSetType | tuple[_DataSetType, dict[float | np.integer | np.floating, ColorLike]][source]#

Add RGB(A) scalars to labeled data.

This filter adds a color array to map label values to specific colors. The mapping can be specified explicitly with a dictionary or implicitly with a colormap or sequence of colors. The implicit mapping is controlled with two coloring modes:

  • 'index' : The input scalar values (label ids) are used as index values for indexing the specified colors. This creates a direct relationship between labels and colors such that a given label will always have the same color, regardless of the number of labels present in the dataset.

    This option is used by default for unsigned 8-bit integer inputs, that is scalars with whole numbers and a maximum range of [0, 255].

  • 'cycle' : The specified colors are cycled through sequentially, and each unique value in the input scalars is assigned a color in increasing order. Unlike with 'index' mode, the colors are not directly mapped to the labels, but instead depends on the number of labels at the input.

    This option is used by default for floating-point inputs or for inputs with values out of the range [0, 255].

By default, a new 'int_rgb' array is added with the same name as the specified scalars but with _rgb appended.

Note

The package colorcet is required to use the default colors from the 'glasbey_category10' colormap. For a similar, but very limited, alternative that does not require colorcet, set colors='tab10' and consider setting the coloring mode explicitly.

Added in version 0.45.

Parameters:
colorsstr | ColorLike | Sequence[ColorLike] | dict[float | str, ColorLike],

Colors to use. Specify a dictionary to explicitly control the mapping from label values to colors. A string key is converted to the data type of the label array. Alternatively, specify colors only using a colormap or a sequence of colors and use coloring_mode to implicitly control the mapping. A single color is also supported to color the entire mesh with one color.

By default,the 'glasbey_category10' categorical colormap is used where the first 10 colors are the same default colors used by matplotlib. See colorcet categorical colormaps for more information.

Note

When a dictionary is specified, any scalar values for which a key is not provided is assigned default RGB(A) values of nan for float colors or 0 for integer colors (see color_type). To ensure the color array has no default values, be sure to provide a mapping for any and all possible input label values.

coloring_mode‘index’ | ‘cycle’, optional

Control how colors are mapped to label values. Has no effect if colors is a dictionary. Specify one of:

  • 'index': The input scalar values (label ids) are used as index values for indexing the specified colors.

  • 'cycle': The specified colors are cycled through sequentially, and each unique value in the input scalars is assigned a color in increasing order. Colors are repeated if there are fewer colors than unique values in the input scalars.

By default, 'index' mode is used if the values can be used to index the input colors, and 'cycle' mode is used otherwise.

color_type‘int_rgb’ | ‘float_rgb’ | ‘int_rgba’ | ‘float_rgba’, default: ‘int_rgb’

Type of the color array to store. By default, the colors are stored as RGB integers to reduce memory usage.

Note

The color type affects the default value for unspecified colors when a dictionary is used. See colors for details.

negative_indexingbool, default: False

Allow indexing colors with negative values. Only valid when coloring_mode is 'index'. This option is useful for coloring data with two independent categories since positive values will be colored differently than negative values.

scalarsstr, optional

Name of scalars with labels. Defaults to currently active scalars.

preferencestr, default: “cell”

When scalars is specified, this is the preferred array type to search for in the dataset. Must be either 'point' or 'cell'.

output_scalarsstr, optional

Name of the color scalars array. By default, the output array is the same as scalars with _rgb or _rgba appended depending on color_type.

return_dictbool, default: False

Return a dictionary with a mapping from label values to the colors applied by the filter. The colors have the same type specified by color_type.

Added in version 0.46.

inplacebool, default: False

If True, the mesh is updated in-place.

Returns:
pyvista.DataSet

Dataset with RGB(A) scalars. Output type matches input type.

dict[float | numpy.integer | numpy.floating, ColorLike]

The label to color mapping, if return_dict is True.

Examples#

Download Python source code | Download Jupyter notebook

Load labeled data and crop it with extract_subset() to simplify the data.

>>> import pyvista as pv
>>> from pyvista import examples
>>> import numpy as np
>>> image_labels = examples.load_channels()
>>> image_labels = image_labels.extract_subset(voi=(75, 109, 75, 109, 85, 100))

Plot the dataset with default coloring using a categorical color map. The plotter by default uniformly samples from all 256 colors in the color map based on the data’s range.

>>> image_labels.plot(cmap='glasbey_category10')
../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_00_00.png

Show label ids of the dataset.

>>> label_ids = np.unique(image_labels.active_scalars)
>>> label_ids
pyvista_ndarray([0, 1, 2, 3, 4]...)

Color the labels with the filter. Note that the 'glasbey_category10' color map is used by default.

>>> colored_labels, color_dict = image_labels.color_labels(return_dict=True)

Plot the labels. We define a helper function to include a legend with the plot.

>>> def labels_plotter(mesh, color_dict):
...     pl = pv.Plotter()
...     pl.add_mesh(mesh)
...     pl.add_legend(color_dict)
...     return pl
>>> labels_plotter(colored_labels, color_dict).show()
../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_01_00.png

Since the labels are unsigned integers, the 'index' coloring mode is used by default. Unlike the uniform sampling used by the plotter in the previous plot, the colormap is instead indexed using the label values. This ensures that labels have a consistent coloring regardless of the input. For example, we can crop the dataset further.

>>> subset_labels = image_labels.extract_subset(voi=(15, 34, 28, 34, 12, 15))

And show that only three labels remain.

>>> label_ids = np.unique(subset_labels.active_scalars)
>>> label_ids
pyvista_ndarray([1, 2, 3]...)

Despite the changes to the dataset, the regions have the same coloring as before.

>>> colored_labels, color_dict = subset_labels.color_labels(return_dict=True)
>>> labels_plotter(colored_labels, color_dict).show()
../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_02_00.png

Use the 'cycle' coloring mode instead to map label values to colors sequentially.

>>> colored_labels, color_dict = subset_labels.color_labels(
...     coloring_mode='cycle', return_dict=True
... )
>>> labels_plotter(colored_labels, color_dict).show()
../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_03_00.png

Map the colors explicitly using a dictionary.

>>> color_dict = {0: 'black', 1: 'red', 2: 'lime', 3: 'blue', 4: 'gold'}
>>> colored_labels = image_labels.color_labels(color_dict)
>>> labels_plotter(colored_labels, color_dict).show()
../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_04_00.png

Omit the background value from the mapping and specify float colors. When floats are specified, values without a mapping are assigned nan values and are not plotted by default.

>>> color_dict.pop(0)
'black'
>>> colored_labels = image_labels.color_labels(
...     color_dict, color_type='float_rgba'
... )
>>> labels_plotter(colored_labels, color_dict).show()
../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_05_00.png

Modify the scalars and make two of the labels negative.

>>> scalars = image_labels.active_scalars
>>> scalars[scalars > 2] *= -1
>>> np.unique(scalars)
pyvista_ndarray([-4, -3,  0,  1,  2]...)

Color the mesh and enable negative_indexing. With this option enabled, the 'index' coloring mode is used by default, and therefore the positive values 0, 1, and 2 are colored with the first, second, and third color in the colormap, respectively. Negative values -3 and -4 are colored with the third-last and fourth-last color in the colormap, respectively.

>>> colored_labels, color_dict = image_labels.color_labels(
...     negative_indexing=True, return_dict=True
... )
>>> labels_plotter(colored_labels, color_dict).show()
../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_06_00.png

If negative_indexing is disabled, the coloring defaults to the 'cycle' coloring mode instead.

>>> colored_labels, color_dict = image_labels.color_labels(
...     negative_indexing=False, return_dict=True
... )
>>> labels_plotter(colored_labels, color_dict).show()
../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_07_00.png

Load the download_foot_bones() dataset.

Label the bones using connectivity() and show the label values.

>>> labeled_data = dataset.connectivity()
>>> np.unique(labeled_data.active_scalars)
pyvista_ndarray([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13,
                 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]...)

Color the dataset with default arguments. Despite having 26 separately colored regions, the colors from the default glasbey-style colormap are all relatively distinct.

../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_08_00.png

Color the mesh with fewer colors than there are label values. In this case the 'cycle' mode is used by default and the colors are reused.

>>> colored_labels = labeled_data.color_labels(['red', 'lime', 'blue'])
>>> colored_labels.plot()
../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_09_00.png

Color all labels with a single color.

../../../_images/pyvista-DataSetFilters-color_labels-5067c09f600cfcba_10_00.png

See Also#

pyvista.DataSetFilters.connectivity

Label data based on its connectivity.

pyvista.ImageDataFilters.contour_labels

Generate contours from labeled images. The contours may be colored with this filter.

pack_labels

Make labeled data contiguous. May be used as a pre-processing step before coloring.