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

Categorical Data is incorrectly colored in the legend when plotting

Open srivarra opened this issue 1 year ago • 0 comments

When using pl.render_labels with the color and palette parameter, the legends are incorrectly colored.

Example Plot: NBL-25-R2C8--Diagnosis--incorrect

Here we see that the Dot plot from scanpy counts 1.1K cells in the cluster NBL_9 and colors them with pastel green (correct color). However on the spatialdata plots, cluster NBL_11 is pastel green, when it should be NBL_9. The colors on the spatialdata image itself are not wrong, it is the colors on the legend which are incorrect.

This issue is occurs in pl.utils._get_palette, where the values in thecategories gets mapped to the colors of the palette. However in scanpy it's the categories of the DataFrame which get mapped to the colors.

By adjusting the following line from https://github.com/scverse/spatialdata-plot/blob/595ea44e2a7414e23d9967ea180d54f4af467b2d/src/spatialdata_plot/pl/utils.py#L753-L754

to dict(zip(categories.categories, palette)) we get the correct legend-color mapping.

NBL-25-R2C8--Diagnosis--correct

Reproducible Example - MIBITOF dataset

import spatialdata as sd
import spatialdata_plot
import matplotlib.pyplot as plt
from pathlib import Path

mibitof_sd = sd.read_zarr(Path("~/Downloads/data.zarr").expanduser())

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(18, 8), layout="tight")

mibitof_sd.pp.get_elements("point8_labels").pl.render_labels(color="Cluster").pl.show(
    ax=axes[0]
)

mibitof_sd.pp.get_elements("point8_labels").pl.render_labels(
    color="Cluster", palette=["blue"], groups=["Epithelial"]
).pl.show(ax=axes[1])

fig

Generated Plot: Here Imm_other in the legend actually represents the Epithelial cells. point8_labels

srivarra avatar Feb 14 '24 19:02 srivarra