spatialdata-plot icon indicating copy to clipboard operation
spatialdata-plot copied to clipboard

Bug in pl.render_shapes which does not let you specify palette and groups

Open sophiamaedler opened this issue 8 months ago • 0 comments

Code to reproduce:

import spatialdata
import spatialdata_plot
sdata = spatialdata.datasets.blobs()

# add some labelling we want to color with a custom defined palette
sdata["table"].obs["labelling"] = (sdata["table"].obs["instance_id"]>10).astype('int').astype('str')
sdata["table"].obs["labelling"] = sdata["table"].obs["labelling"].astype('category')

# with labels it works
sdata.pl.render_labels("blobs_labels", color = "labelling", palette = ["red", "blue"], groups = ["0", "1"]).pl.show()

# transform to shapes and add necessary annotation
sdata["test_labels"] = spatialdata.to_polygons(sdata["blobs_labels"])

adata = sdata["table"].copy()
adata.obs["region"] = "test_labels"
adata.uns["spatialdata_attrs"]["region"] = "test_labels"
sdata["test_annotation"] = spatialdata.models.TableModel.parse(adata)

# with shapes it throws an error
sdata.pl.render_shapes("test_labels", color = "labelling", palette = ["red", "blue"], groups = ["0", "1"]).pl.show()

Error message:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/35/p4c58_4n3bb0bxnzgns1t7kh0000gn/T/ipykernel_76317/1461128882.py in ?()
      5 adata.obs["region"] = "test_labels"
      6 adata.uns["spatialdata_attrs"]["region"] = "test_labels"
      7 sdata["test_annotation"] = spatialdata.models.TableModel.parse(adata)
      8 
----> 9 sdata.pl.render_shapes("test_labels", color = "labelling", palette = ["red", "blue"], groups = ["0", "1"]).pl.show()

~/Documents/GitHub/spatialdata-plot/src/spatialdata_plot/pl/basic.py in ?(self, coordinate_systems, legend_fontsize, legend_fontweight, legend_loc, legend_fontoutline, na_in_legend, colorbar, wspace, hspace, ncols, frameon, figsize, dpi, fig, title, share_extent, pad_extent, ax, return_ax, save)
    932                         sdata, wanted_elements, params_copy, cs, "shapes"
    933                     )
    934 
    935                     if wanted_shapes_on_this_cs:
--> 936                         _render_shapes(
    937                             sdata=sdata,
    938                             render_params=params_copy,
    939                             coordinate_system=cs,

~/Documents/GitHub/spatialdata-plot/src/spatialdata_plot/pl/render.py in ?(sdata, render_params, coordinate_system, ax, fig_params, scalebar_params, legend_params)
    135     # filter by `groups`
    136     if isinstance(groups, list) and color_source_vector is not None:
    137         mask = color_source_vector.isin(groups)
    138         shapes = shapes[mask]
--> 139         shapes = shapes.reset_index()
    140         color_source_vector = color_source_vector[mask]
    141         color_vector = color_vector[mask]
    142 

~/mambaforge/envs/scportrait/lib/python3.11/site-packages/pandas/core/frame.py in ?(self, level, drop, inplace, col_level, col_fill, allow_duplicates, names)
   6468                     level_values = algorithms.take(
   6469                         level_values, lab, allow_fill=True, fill_value=lev._na_value
   6470                     )
   6471 
-> 6472                 new_obj.insert(
   6473                     0,
   6474                     name,
   6475                     level_values,

~/mambaforge/envs/scportrait/lib/python3.11/site-packages/pandas/core/frame.py in ?(self, loc, column, value, allow_duplicates)
   5154                 "'self.flags.allows_duplicate_labels' is False."
   5155             )
   5156         if not allow_duplicates and column in self.columns:
   5157             # Should this be a different kind of error??
-> 5158             raise ValueError(f"cannot insert {column}, already exists")
   5159         if not is_integer(loc):
   5160             raise TypeError("loc must be int")
   5161         # convert non stdlib ints to satisfy typing checks

ValueError: cannot insert label, already exists

Without specifying palette and groups the code runs fine and generates the expected result:

sdata.pl.render_labels("blobs_labels", color = "labelling").pl.show()

Image

sophiamaedler avatar May 18 '25 20:05 sophiamaedler