Skip to content

Extend make_palette_from_data to support labels elements #662

@timtreis

Description

@timtreis

Summary

sdp.pl.make_palette_from_data(sdata, element, color, ...) currently raises KeyError when element is a labels (raster) element:

KeyError: "Element 'blobs_labels' not found in sdata.shapes or sdata.points.
Available elements: [...]. Note: labels (raster) elements are not yet supported."

Source: _resolve_element in src/spatialdata_plot/pl/_palette.py:278–306. The error message itself flags this as a TODO ("not yet supported"), so this is a known gap rather than a principled exclusion.

Why it's worth doing

  • render_labels accepts palette=, so users naturally expect make_palette_from_data to produce one for labels too.
  • For labels, the categorical column lives on the linked AnnData table (adata.obs[<col>]) — this is actually simpler than the current shapes/points path, which checks the GeoDataFrame first and only falls back to the table.
  • Without it, users get a clean {category: hex} dict for shapes/points but have to hand-roll one for labels. The asymmetry is surprising and breaks the "one helper for any categorical" mental model.
  • It bites the upcoming color/palette tutorial notebook (Adding plotting specific documentation #463): the most natural example (categorical coloring of segmentation masks) doesn't work; we currently demo it on polygons instead.

Proposed scope

  1. Extend _resolve_element (src/spatialdata_plot/pl/_palette.py:278) to handle labels: when element is in sdata.labels, skip the GeoDataFrame branch and resolve the column from the linked table directly.
  2. Reuse table_name argument resolution analogous to _validate_col_for_column_table (src/spatialdata_plot/pl/utils.py:3155–3163) for the multi-table-annotates-the-same-element case.
  3. Update the make_palette_from_data docstring to drop the "shapes or points" restriction.
  4. Add a regression test mirroring the existing shapes/points coverage (a labels element with a categorical column in the linked table → expected {category: hex} dict).

Estimated diff: ~30–50 LOC plus tests. No public API change; only widens an existing function.

Open questions

  • Should NaN values in the categorical column produce a na_color key in the returned dict, or be omitted? Match whatever render_labels(palette=..., na_color=...) does today.
  • For labels annotated by multiple tables without table_name= set, raise the same error as the shapes/points path (don't pick silently).

Filed alongside #463 (plotting documentation) — the new color tutorial currently sidesteps this by using blobs_polygons instead of blobs_labels for the §5 demo.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions