Skip to content

Plotting Leiden clusters, coloring by cell cycle phase, throws KeyError: 'geometry' #455

Open
@marcouderzo

Description

@marcouderzo

Hello,
I need to plot the spatial locations of bins belonging to leiden clusters (one cluster per plot), but the color of each bin plotted should be colored based on the cell cycle phase

Here's my code:

clusters = sdata["table"].obs["clusters"].unique()

for cluster in clusters:
    sdata.pl.render_images('22WT-1_hires_image-wt1', cmap='gray').pl.render_shapes(
        'locations-wt1',
        color="ccAFv2_wG0",
        groups=[cluster],
        size=0.3,
        method='matplotlib'
    ).pl.show(
        coordinate_systems="22WT-1_downscaled_hires",
        figsize=(20, 20)
    )

INFO     Rasterizing image for faster rendering.

[/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata/_core/spatialdata.py:185](https://192.33.153.114/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata/_core/spatialdata.py#line=184): UserWarning: The table is annotating 'locations-wt5', which is not present in the SpatialData object.
  self.validate_table_in_spatialdata(v)
[/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata/_core/spatialdata.py:185](https://192.33.153.114/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata/_core/spatialdata.py#line=184): UserWarning: The table is annotating 'locations-wt8', which is not present in the SpatialData object.
  self.validate_table_in_spatialdata(v)

WARNING  One cmap was given for multiple channels and is now used for each channel. You're blending multiple cmaps.
         If the plot doesn't look like you expect, it might be because your cmaps go from a given color to 'white',
         and not to 'transparent'. Therefore, the 'white' of higher layers will overlay the lower layers. Consider
         using 'palette' instead.

[/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata/_core/_elements.py:105](https://192.33.153.114/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata/_core/_elements.py#line=104): UserWarning: Key `locations-wt1` already exists. Overwriting it in-memory.
  self._check_key(key, self.keys(), self._shared_keys)
[/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata/_core/_elements.py:125](https://192.33.153.114/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata/_core/_elements.py#line=124): UserWarning: Key `table` already exists. Overwriting it in-memory.
  self._check_key(key, self.keys(), self._shared_keys)
[/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata_plot/pl/utils.py:771](https://192.33.153.114/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata_plot/pl/utils.py#line=770): FutureWarning: The default value of 'ignore' for the `na_action` parameter in pandas.Categorical.map is deprecated and will be changed to 'None' in a future version. Please set na_action to the desired value to avoid seeing this warning
  color_vector = color_source_vector.map(color_mapping)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[50], line 4
      1 clusters = sdata["table"].obs["clusters"].unique()
      3 for cluster in clusters:
----> 4     sdata.pl.render_images('22WT-1_hires_image-wt1', cmap='gray').pl.render_shapes(
      5 'locations-wt1',
      6 color="ccAFv2_wG0",
      7 groups=[cluster],
      8 size=0.3,
      9 method='matplotlib'
     10 ).pl.show(
     11 coordinate_systems="22WT-1_downscaled_hires",
     12 figsize=(20, 20)
     13 )

File [/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata_plot/pl/basic.py:937](https://192.33.153.114/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata_plot/pl/basic.py#line=936), in PlotAccessor.show(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     wanted_elements, wanted_shapes_on_this_cs, wants_shapes = _get_wanted_render_elements(
    933         sdata, wanted_elements, params_copy, cs, "shapes"
    934     )
    936     if wanted_shapes_on_this_cs:
--> 937         _render_shapes(
    938 sdata=sdata,
    939 render_params=params_copy,
    940 coordinate_system=cs,
    941 ax=ax,
    942 fig_params=fig_params,
    943 scalebar_params=scalebar_params,
    944 legend_params=legend_params,
    945 )
    947 elif cmd == "render_points" and has_points:
    948     wanted_elements, wanted_points_on_this_cs, wants_points = _get_wanted_render_elements(
    949         sdata, wanted_elements, params_copy, cs, "points"
    950     )

File [/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata_plot/pl/render.py:333](https://192.33.153.114/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata_plot/pl/render.py#line=332), in _render_shapes(sdata, render_params, coordinate_system, ax, fig_params, scalebar_params, legend_params)
    327         cax = ScalarMappable(
    328             norm=matplotlib.colors.Normalize(vmin=vmin, vmax=vmax),
    329             cmap=render_params.cmap_params.cmap,
    330         )
    332 elif method == "matplotlib":
--> 333     _cax = _get_collection_shape(
    334 shapes=shapes,
    335 s=render_params.scale,
    336 c=color_vector,
    337 render_params=render_params,
    338 rasterized=sc_settings._vector_friendly,
    339 cmap=render_params.cmap_params.cmap,
    340 norm=norm,
    341 fill_alpha=render_params.fill_alpha,
    342 outline_alpha=render_params.outline_alpha,
    343 zorder=render_params.zorder,
    344 # **kwargs,
    345 )
    346     cax = ax.add_collection(_cax)
    348     # Transform the paths in PatchCollection

File [/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata_plot/pl/utils.py:443](https://192.33.153.114/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/spatialdata_plot/pl/utils.py#line=442), in _get_collection_shape(shapes, c, s, norm, render_params, fill_alpha, outline_alpha, **kwargs)
    439     return pd.DataFrame(rows)
    441 patches = _create_patches(shapes_df, fill_c, outline_c, s)
    442 return PatchCollection(
--> 443     patches["geometry"].values.tolist(),
    444     snap=False,
    445     lw=render_params.outline_params.linewidth,
    446     facecolor=patches["fill_c"],
    447     edgecolor=None if all(outline is None for outline in outline_c) else outline_c,
    448     **kwargs,
    449 )

File [/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/pandas/core/frame.py:4102](https://192.33.153.114/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/pandas/core/frame.py#line=4101), in DataFrame.__getitem__(self, key)
   4100 if self.columns.nlevels > 1:
   4101     return self._getitem_multilevel(key)
-> 4102 indexer = self.columns.get_loc(key)
   4103 if is_integer(indexer):
   4104     indexer = [indexer]

File [/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/pandas/core/indexes/range.py:417](https://192.33.153.114/opt/conda/envs/spatialdatahd/lib/python3.10/site-packages/pandas/core/indexes/range.py#line=416), in RangeIndex.get_loc(self, key)
    415         raise KeyError(key) from err
    416 if isinstance(key, Hashable):
--> 417     raise KeyError(key)
    418 self._check_indexing_error(key)
    419 raise KeyError(key)

KeyError: 'geometry'

I am attaching screenshots of the .obs and shapes.

Image
Image

The data was segmented with Bin2Cell using the 2um binning, but plotting just the clusters works fine.
Is this a bug or am I using the function incorrectly? What should the correct workflow be?

Thank you!

Best Regards,

Marco Uderzo

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